public function update_room_detail(Request $request)
{
$request->validate([
'room_type' => 'required',
]);
if($images = $request->file('room_image'))
{
foreach($images as $item):
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time.'-'.$item->getClientOriginalName();
$item->move(public_path().'/assets/images/room', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode("|", $arr);
}
else
{
unset($image);
}
RoomDetail::where('id',$request->room_id)->update([
'room_type' => $request->room_type,
'room_image' => $image,
]);
Alert::success('Success', 'Rooms details updated!');
return redirect()->route('admin.manage-room');
}
In the above code I am trying to update image in database table. When I click on submit button then it show Undefined variable: image and when I use $image='' in else part instead of unset($image) then blank image name save. So, How can I solve this issue please help me? Please help me.
Thank You
As per the PHP documentation:
unset() destroys the specified variables.
What this means is that it doesn't empty the value of the specified variables, they are destroyed completely.
$foo = "bar";
// outputs bar
echo $foo;
unset($foo);
// results in Warning: Undefined variable $foo
echo $foo;
You've already discovered how to handle this:
when I use $image='' in else part instead of unset($image) then blank image name save
Fix:
Note : uses Storage library feel free to use any other.
public function update_room_detail(Request $request)
{
$request->validate([
'room_type' => 'required',
]);
$imageNames = array();
if ($request->hasFile('room_image')) {
$images = $request->file('room_image');
foreach ($images as $item) {
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time . '-' . $item->getClientOriginalName() .".".$item->extension();
$item->storeAs('/public/room-images-path', $imageName);
array_push($imageNames, $imageName);
}
}
RoomDetail::where('id', $request->room_id)->update([
'room_type' => $request->room_type,
'room_image' => $imageNames,
]);
Alert::success('Success', 'Rooms details updated!');
return redirect()->route('admin.manage-room');
}
Related
i am trying to do a login with sessions but it doesn't seem to be working because when i log in the session data on the view is not being displayed. once logged in it should read something like: 'Welcome Jon' but it doesn't. What could be the issue
controller fn
function login_user()
{
if(isset($_POST['login']))
{
$data = $this->Model_students->fetchUserData();
if(!empty($data))
{
var_dump($data);
foreach ($data as $key => $value) :
$user_id = $value->id;
$firstname = $value->firstname;
$lastname = $value->lastname;
$grade = $value->grade;
$email = $value->email;
$images = json_decode($value->userfile);
endforeach;
$user_info = array(
'id' => $user_id,
'firstname' => $firstname,
'lastname' => $lastname,
'grade' => $grade,
'email' => $email,
'images' => $images[0]->file_name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($user_info);
redirect('Students/homepage');
}
else
{
$this->session->set_flashdata('error', 'Error! Invalid username or password');
redirect('Students/login_user');
}
}
else
{
$this->load->view('signup');
}
}
model
the join here is for a different table in the same db where the common row is id..not sure if the join is correct too
public function fetchUserData()
{
$this->db->select('users.*, user_images.*');
$this->db->from('users');
$this->db->join('user_images', 'users.id=user_images.user', 'inner');
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get();
if($query->num_rows() == 1 ) :
foreach($query->result() as $row):
$data[] = $row;
endforeach;
return $data;
endif;
}
view the img scr here should display the user image based on what is saved on the db when he/she first registered
</head>
<body>
<h3>Welcome <?php $this->session->userdata('$firstname')?>.</h3>;
<img class ="img-circle" src="<?=base_url();?>uploads/users/<?=$this->session->userdata('userfile/file_name');?>" width="250" height="auto">
There's a typo in your views. where the session variable should be without the $ symbol.
<h3>Welcome <?php echo $this->session->userdata('firstname'); ?>.</h3>;
Also, check if the $user_info contains the expected data. Do a var_dump($user_info) and see just before creating the session.
there could be many issues with it.
1: your are passing a variable in the string which is not valid ( $this->session->userdata('$firstname') ) remove the $ from the first name;
2: there has to be a constructor in the controller so that the session could be called when ever the object is created;
hope it will solve your problem
I want to make laravel api for multiple file upload when i am uploading then its gives error $data is undefined variable.please help me how to remove this error..?
FileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function uploadFile(Request $request){
$this->validate($request, [
'user_sharing_image' => 'required',
'user_sharing_image.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = $request->user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
return back()->with('success', 'Data Your files has been successfully added');
}
}
I am using laravel passport for auth and want to store user_id but do not geting please help me how to resolve both problem from this code
Give it a try
$data = [];
if($request->hasfile('user_sharing_image'))
{
foreach($request->file('user_sharing_image') as $key=>$file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[$key] = $name;
}
}
$file= new Detail();
$file->title = $request->title;
$file->info = $request->info;
$file->user_id = Auth::user()->id;
$file->user_sharing_image=json_encode($data);
$file->save();
You are getting this error because $data is not defined.
Before foreach loop you can declare it as $data = array();
i think you should use files method to return array of files :
foreach($request->files('user_sharing_image') as $file)
Hello fellow developers
This will work properly
$files = $request->allFiles('imgs');
foreach ($files as $key => $img) {
# code...
$filename = request()->getSchemeAndHttpHost() . '/assets/images/users/upload/profile/photos/' . time() . '.'. $img->extension();
$img->move(public_path('/assets/images/users/upload/profile/photos/'), $filename);
$photos = UserPhoto::create([
'user_id' => $user->id,
'name' => $filename
]);
}
return response()->json([
'status' => true,
'data' => 'Photos Uploaded Successfully!!'
]);
I created a form here with Laravel and DropzoneJS and I tried uploading a Gimp file (.xcf) and when it is uploaded it is saved in S3 as the following
<random-name>.
without the "xcf" extension just random name ending with a dot.
Also, I created a text file and renamed it to test.xcf when I tried uploading that file it was uploaded with the .txt extension.
Here is my UploadController.php which handles the upload:
<?php
namespace App\Http\Controllers;
use App\Upload;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function upload(Request $request)
{
$originalName = $request->file('file')->getClientOriginalName();
$fileSize = $request->file('file')->getClientSize();
$path = $request->file('file')->store('documents');
$explode = explode('documents/', $path);
$name = $explode[1];
$uniqueId = $this->generateUniqueId();
$upload = new Upload();
$upload->unique_id = $uniqueId;
$upload->name = $name;
$upload->path = $path;
$upload->original_name = $originalName;
$upload->size = $fileSize;
if ($upload->save())
{
return response()->json([
'original_name' => $originalName,
'size' => $fileSize,
'url' => env('AWS_URL') . $path,
'id' => $uniqueId,
'status' => 'OK'
]);
}
return response()->json(['status' => 'BAD', 'message' => 'There was a problem saving your file.']);
}
public function generateUniqueId()
{
$result = '1';
$result .= rand(100000000, 999999999);
while(Upload::where('unique_id', '=', $result)->first())
{
$result = '1';
$result .= rand(100000000, 999999999);
}
return $result;
}
}
I've got no idea why it's doing that.
I suggest, you generate your own hash for filename, like I do in this code:
$file = $request->file('csv');
$path = $file->storeAs(
'csv',
md5($file->getClientOriginalName()) . $file->getClientOriginalExtension(),
's3'
);
You can also add uniqid() to md5 input
If you're using laravel 5+ then you should get the extension also using this.
$extension = $file->getClientOriginalExtension();
This will work fine.
I upgraded from Laravel 4.2 to Laraveld5.3 with intervention/image : "^2.3",
if (Input::hasFile('logo')) {
$path = public_path()."/assets/admin/layout/img/";
File::makeDirectory($path, $mode = 0777, true, true);
$image = Input::file('logo');
$extension = $image->getClientOriginalExtension();
$filename = "logo.$extension";
$filename_big = "logo-big.$extension";
Image::make($image->getRealPath())->save($path.$filename);
Image::make($image->getRealPath())->save($path.$filename_big);
$data['logo'] = $filename;
}
The result Is, got the error below:
Call to undefined method Intervention\Image\Facades\Image::make()
I experienced the same issue in my Laravel 5.4 project. I stumble on this link
that help resolve the issue. This was the fix that was provided
In config/app change 'aliases' for Image from
'Image' => Intervention\Image\Facades\Image::class,
To
'Image' => Intervention\Image\ImageManagerStatic::class,
Then in your controller header add
use Image;
Make Sure that
In config/app update Providers with
Intervention\Image\ImageServiceProvider::class
and update aliases with
'Image' => Intervention\Image\Facades\Image::class,
In your config/app.php file, add
Intervention\Image\ImageServiceProvider::class,
in providers array and add
'Image' => Intervention\Image\Facades\Image::class,
in aliases array.
Run
php artisan config:cache
command.
In your controller add
use Image;
before class definition.
Now you can use the Image class according to your needs inside the controller's function. suppose,
$imageHeight = Image::make($request->file('file'))->height();
public function optimizeFile(Request $request)
{
$data = $request->file('image');
// dd($data);
if ($request->hasFile('image')) {
foreach($data as $key => $val){
$path=storage_Path('app/public/');
$filename='image-'.uniqid().$key.'.'.'webp';
$val->move($path,$filename);
$p['image']=$filename;
$insert[$key]['image'] = $filename;
//Resize image here
$thumbnailpath[$key]['abc'] = storage_path('app/public/'.$filename);
$img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) {
$constraint->aspectRatio();
});
$img->save($thumbnailpath);
}
return redirect('ROUTE_URL')->with('success', "Image uploaded successfully.");
}
}
I have an issue in parsing variable.
I have dynamic email template for all types of email like registration,activation and so on
Suppose i want to send feedback email and i have email template for feedback stored in database.
In database it is stored as Name:{{ $name }}
But when i sent email it is sending Name:{{ $name }} instead of actual name like Name:john
Following is my code:
$name = $request->get('name');
$address = $request->get('address');
$phone = $request->get('phone');
$emailaddress = $request->get('email_address');
$feedbacktext = $request->get`enter code here`('message');
Mail::send('lugmety.frontend.partials.contactUsEmail',
[ 'name' => $name,
],
function ($mail)
use ($address, $name,$phone,$emailaddress,$feedbacktext) {
$mail->to('anandshrestha57#gmail.com')->subject('FeedBack Form')->from($emailaddress,$name);
});
Here is my view which contains email template obtained from database.
<?php echo \App\EmailTemplate::where('slug','contact-us')->first()->body; ?>
Thanks for help.
private function parsed_content($email_template, array $args = array()){
$generated = \Blade::compileString($email_template);
ob_start() and extract($args, EXTR_SKIP);
try{
eval('?>'.$generated);
}catch (\Exception $e){
b_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
}
And for parsing variable in email template stored in database:
$emailTemplate = EmailTemplate::where('slug','contact-us')->first();
$email_body = $this->parsed_content($emailTemplate, array(
'name' => $name,
'address' => $address,
'phone' => $phone,
'emailaddress' => $emailaddress,
'feedbacktext'=>$feedbacktext
));
$body = json_decode($email_body,true)['body'];
And for sending email:
Mail::send([],[],
function ($mail)
use ($body,$address, $name,$phone,$emailaddress,$feedbacktext) {
$mail->to('anandshrestha57#gmail.com')->subject('FeedBack Form')->from($emailaddress,$name)
->setBody($body,'text/html');
});
So no need of making every view. Source:#Is there any way to compile a blade template from a string?
Add a function in EmailTemplate Model
//$value is $EmailTemplate->body value
public function getBodyAttribute($value)
{
//get value name by request function
$name = request()->get('name');
//do your regex code to replace {{ name }} from $name in $value and update.....
//finaly return $value;
return $value;
}