RESOLVED Laravel 8 Update image and delete old image - laravel

I need help with a little thing.
I have a product table with an image:
Here is my function store which works perfectly
$fileName = null;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
Product::create([
'title' => $request->input('title'),
'subtitle' => $request->input('subtitle'),
'description' => $request->input('description'),
'price' => $request->input('price'),
'image' => $fileName,
]);
I am trying to modify the image in update but I do not know how to do it and I am in difficulty currently
Here is my update function where the image is missing to modify it and delete the old one
public function update(Request $request, Product $product)
{
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->save();
Thanks

You can modify your update function like this
public function update(Request $request, Product $product)
{
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage
if($fileName && $currentImage)
{
// Delete the old file i.e $fileName
}
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->image = $fileName;
$product->save();
}

It's good with this :
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage;
if($fileName && $currentImage)
{
Storage::delete('./img/' . $currentImage);
}
Thanks

Related

Laravel upload gifs

i am uploading gif for my posts in laravel but gif is like an image its not moving or something like this
<?php
if($request->hasFile('gif')){
$gif = $request->file('gif');
$gif_filename = time() . '.' . $gif->getClientOriginalName();
$gif_location = public_path('/images/' . $gif_filename);
Image::make($gif)->save($gif_location);
}
$post->gif = $gif_filename;
$post->save();
?>
here is the code what I am using I think everything is kinda correct
I use this method
if(Input::hasFile('imagen')) {
$time = Carbon::now()->format('Y-m-d');
$image = $request->file('imagen');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = $time."-".$name;
$image->move(storage_path(),$fileName);
}
Please try this and let me know how it works :)
An easy way to update and save is to do it like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('gif'));
// This would save it to the gifs table if you need something like it, otherwise skip this creation
$gif= Gif::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($gif) {
return response()->json("Success!");
}
return response()->json("Error!"); // or you return redirect()...
}
$image = $request->file('image');
if(isset($image)) {
if($image->getClientOriginalExtension()=='gif'){
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = 'exerciseimages'."-".$name;
$image->move('storage/courseimages/',$fileName);
}
else{
$fileName = 'exerciseimages'.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('courseimages')){
Storage::disk('public')->makeDirectory('courseimages');
}
$amenitiesimg = Image::make($image)->resize(250,250)->stream();
Storage::disk('public')->put('courseimages/'.$fileName, $amenitiesimg);
}
}
else {
$fileName = 'default.png';
}

I am trying to upload multiple images in laravel and facing issues as the same image is uploaded each time?

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.

laravel using switch cases to upload files

how can i upload inputs files in different folders i need to use switch cases to make every input file in different folder and did this code but when i execute it nothing happen i want know where problem
my view
{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}
my controler
$model = new Files($request->all());
switch ($model) {
case "file1":
if ($request->hasFile('file1')) {
$file = $request->file('file1');
$destinationPath = public_path() . '/file1';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file1'] = $filename;
$model -> file1 = $filename;
$model->save();
}
break;
case "file2":
if ($request->hasFile('file2')) {
$file = $request->file('file2');
$destinationPath = public_path() . '/file2';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file2'] = $filename;
$model->file2 = $filename;
$model->save();
}
break;
case "file3":
if ($request->hasFile('file3')) {
$file = $request->file('file3');
$destinationPath = public_path() . '/file3';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file3'] = $filename;
$model->file3 = $filename;
$model->save();
}
break;
case "file4":
if ($request->hasFile('file4')) {
$file = $request->file('file4');
$destinationPath = public_path() . '/file4';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file4'] = $filename;
$model->file4 = $filename;
$model->save();
}
break;
}
Ummm yeah I had do something like that, but I do it use foreach loop and if after that.
And here's my sample code, I hope it can help :-D
$requests = $request->all();
$model = new File;
foreach ($requests as $key => $val) {
if ($key == 'file1' && !empty($val)) {
$destinationPath = public_path() . '/file1';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
if ($key == 'file2' && !empty($val)) {
$destinationPath = public_path() . '/file2';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
// And do it again as much as you need :D
}
Here you go, I hope it can help you pals :D

i m saving the multiple images at a single time with differnt ID in database in Laravel

and it is saved but the issue is all the images have different auto
increment ids in database i want to save the images with the same ids
which is save at the same time,kindly guide me.
****strong text** the code is below;**
$field = Input::file('image');
$location = public_path('uploads/');
foreach ($field as $k => $fd) {
$filename = str_random(2).'-' . time() . "." . $fd->getClientOriginalExtension();
$fd->move($location , $filename);
$product->image = $filename;
}
$user->save();
I think bellow code helps you..
You can try.
$picture = '';
if ($request->hasFile('image')) {
$files = $request->file('image');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}

laravel uploading pic path showing zero

WHen uploading, all data is inserted in table except pic_path column contains 0. Am i doing wrong when processing file uploaded:
This is the controller:
if(Session::has('userLogged'))
{
if($_POST)
{
$file;
if (Input::hasFile('pic'))
{
$file = Input::file('pic');
print_r($file);
}
$validator = $this->validate(Input::all(), $rules);
if ($validator != null)
{
return Redirect::to('basicDetails')->withErrors($validator);
}else{
$title = Input::get('title');
$summary = Input::get('summary');
$description = Input::get('description');
$destinationPath = base_path() . '/public/img';
$file->move($destinationPath);
$path = $file->getRealPath();
$personModel = new Course;
$personeModel->basicDetails($title, $summary, $description, $path);
}
and this is form url:
{{ Form::open(array('action' => 'PersonController#basic','files' => true)) }}
Thanks,
Before move the file get the path:
$title = Input::get('title');
$summary = Input::get('summary');
$description = Input::get('description');
$destinationPath = base_path() . '/public/img';
$path = $file->getRealPath();
$file->move($destinationPath);
$personModel = new Course;
$personeModel->basicDetails($title, $summary, $description, $path);
I am not sure why you need uploaded path? Usually this is the temp path where Laravel uploaded the file.
http://laravel.com/docs/requests#files

Resources