I want to upload image using laravel 8, and I use following code:
$post = new Post;
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
It is working fine, but I got error Call to a member function getClientOriginalName() on null while image is empty.
It's because, suprise, image is empty while image is empty
Add condition to check uploaded image
$post = new Post;
$post->title = $req->input('title');
if($req->image_name)
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->image_name = $upload_image_name;
}
$post->save();
If image is required - add validation in action beginning - but right way for it - make validation in Form Request
$request->validate([
'image_name' => 'required|image',
'title' => 'required|string'
]);
If image is not required - change your migration and make posts.image_name nullable
I use following code but I don't think this is conventional way. Here is the code:
if($req->hasFile('image_name')){
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
}
else
$upload_image_name = "Noimage";
$post = new Post;
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
As I used my last laravel project.
$image = $request->file('thumbnail');
if (isset($image)) {
$imageName = date('y_m_d') . "_" . uniqid().".".$image->getClientOriginalExtension();
if (!Storage::disk('public')->exists('thumbnail')) {
Storage::disk('public')->makeDirectory('thumbnail');
}
$postImage = Image::make($image)->stream();
Storage::disk('public')->put('thumbnail/' . $imageName, $postImage);
} else {
$imageName = "";
}
$post = new Post;
$post->title = $request->title;
$post->image_name = $imageName;
$post->save();
image_name column should be nullable.
Related
I want to store images with id to table and save them to a folder.
I have two tables catalogs and images.Images table has img_id which is a foreign key to id in catalogs table, code in my controller is:
$catalog = new Katalog();
$catalog->name = $name;
$catalog->picturePath = $name . '/';
$catalog->description = $desc;
$catalog->address = $request->input('address');
$catalog->phone_number = $request->input('phone_number');
$catalog->email = $request->input('e_mail');
$catalog->info_holder = $request->input('type');
$catalog->partner_logo = $logo_img_name;
$catalog->short_news = $request->input('short_news');
$catalog->updated_at = Carbon::now();
$catalog->site = $request->input('site');
$catalog->creator_id = Auth::user()->id;
$catalog->save();
$id = Katalog::where('name', $name)->first()->id;
if ($request->hasFile('images')) {
foreach ($request->file('images') as $image) {
$img_name = $image->getClientOriginalName();
$request->image->storeAs(('/images/' . $name), $img_name, 'images');
Image::creat([
'img_id' => $id,
'img_name' => $img_name
]);
}
}
After storing data to the catalogs table it returns a new id but I want to store images to images table with returned id but can not do this.Error shows here $request->image->storeAs(('/images/' . $name), $img_name, 'images');
Help me please thanks in advance.
You can get the ID from the just created object (Katalog) without a query
$id = $catalog->id;
instead of
$id = Katalog::where('name', $name)->first()->id;
Because if there are other Katalog records with the same name, you may not get the one you want
PS: you may have a typo here, add an "e" at the end
Image::create([
'img_id' => $id,
'img_name' => $img_name
]);
Hope this helps
I have the form of a service where a name, description, and photo is required. When adding a new service the form works fine, everything is saved in the database.
Problem is when I want to change the photo and upload a new one its not working.
**Here is my controller method **, for both adding and updating service
public function post(ServiceRequest $request, Service $service)
{
$service = Service::firstOrNew(['id' => $request->get('id')]);
$service->id = $request->get('id');
$service->name = $request->get('name');
$service->description = $request->get('description');
$image = $request->file('photo')->store('services/');
$service->photo = $image;
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$name = time() . $service->name . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $name);
}
if ($request->has('photo')) {
$image = $request->file('photo');
}
$service->save();
Alert::success('Service Saved');
return redirect()->back();
// dd($service);
}
I need some assistance with updating the image and removing an old one that was added on update record.
The problem is that my loop only running and uploading the same first pic each time rather than uploading each other in a row one after one!
Here is my code of the form
{!! Form::file('photos[]', ['roles' => 'form', 'class' => 'form-control-file','multiple' => true]) !!}
Here is my code of the controller
$files=$request->file('photos');
foreach ($files as $file) {
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$file->getClientOriginalExtension();
$insert->Save();
$uid = $insert->id;
$file->move($destinationPath,$imageName);
$image = array(
'youth_fashion_images_img' => $imageName
);
Images::where('youth_fashion_images_id',$uid)->update($image);
}
return redirect('adminpanel/viewimages');
Try this code :
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$image->getClientOriginalExtension();
$image->move($destinationPath,$imageName);
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$insert->youth_fashion_images_img = $imageName;
$insert->Save();
}
}
You should try this code.
if($request->hasfile('photos')) {
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$name = 'uploads/products/'.time().'.'.$image->getClientOriginalName();
$image->move($destinationPath, $name);
$data[] = $name;
}
}
$insert= new Images;
$insert->youth_fashion_images_img = json_encode($data);
$insert->save();
json_encode to insert the multiple image names in one row.
So add $name in array $data[] = $name;.
I hope this will helps.
recently i'm trying to practice with laravel 5.5 and create simple upload and update image
here is my controller on store
$input = $request->all();
$this->validate($request, [
'photo' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$photo_name = date('YmdHis'). ".$ext";
$photoName = time().'.'.$request->photo->getClientOriginalExtension();
$request->photo->move(public_path('photo-upload'), $photoName);
$upload_path = public_path('photo-upload');
$input['photo'] = $photoName;
}
}
controller update
if ($request->hasFile('photo')) {
// delete the old/previous one
$exist = Storage::disk('photo')->exists($student->photo);
if (isset($student->photo) && $exist) {
$delete = Storage::disk('photo')->delete($siswa->photo);
}
// upload new one
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
$photoName = time().'.'.$request->foto->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$upload_path = 'photo-upload';
$request->file('photo')->move($upload_path, $phptpName);
$input['photo'] = $iphotoName;
}
}
the store method works perfectly, it uploaded image to the right folder then update the databse
the problem is on the update, it update the database but it didn't upload the image to the photo-upload folder
Any suggestion?
Thanks
I have a little problem about update avatar pic of my user.
I have a polymorph relation table for Image and when i update info of my user profile and upload new avatar in my DB he create a new entry and not updated the current id of my table Images.
Table Images Id|path|Imageable_id|imageable_type|created_at
My UsersController method update
public function update($id){
$rules =[
/*'lastname' => 'min:3|string',
'firstname' => 'min:3|string',
'username'=> 'min:4|unique:users',
'mail' => ' email|unique:users',
'birthday' => 'date_format:d-m-Y|before:today',
'country'=>'min:3',
'type_street'=>'min:3',
'number'=>'min:1|numeric',
'street'=>'min:4|string',
'complementary_street'=>'min:2|string',
'town'=>'min:2|string',
'zip'=>'min:4|numeric',
'phone_home'=>'min:10|numeric',
'phone_mobile'=>'min:10|numeric',
'image_path'=>'image|max:1000|mimes:jpeg,jpg,png',*/
];
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::to('/profil/'.$id)
->with('alert_error','Merci de corriger les erreurs');
}else{
$user = User::find($id);
$user->lastname = Input::get('lastname');
$user->firstname = Input::get('firstname');
$user->username = Input::get('username');
$user->mail = Input::get('mail');
$user->birthday = Input::get('birthday');
$user->adresse->type_street = Input::get('type_street');
$user->adresse->number = Input::get('number');
$user->adresse->street = Input::get('street');
$user->adresse->complementary_street = Input::get('complementary_street');
$user->adresse->town = Input::get('town');
$user->adresse->zip = Input::get('zip');
$user->adresse->country = Input::get('country');
$user->adresse->phone_home = Input::get('phone_home');
$user->adresse->phone_mobile = Input::get('phone_mobile');
if(Input::hasFile('avatar')){
$avatar = Image::find($id);
$file = Input::file('avatar');
$name = time().'-'.$file->getClientOriginalName();
$file = $file->move('img/avatar/', $name);
$input['path'] = 'img/avatar/'.$name;
$input['imageable_id'] = $user->id;
$input['imageable_type'] = 'User';
$avatar = new Image($input);
$avatar->save();
}
$user->adresse->save();
return Redirect::to('/profil/'.$id)
->with('alert_success','Modification sauvegardé avec succès');
}
}
Can you help me for this feature i don't understand why no updated of current id of my entry and create new One .
Thank's
You're overwriting your find $avatar = Image::find($id); with a new instance $avatar = new Image($input);