Your $location seems to be the full path of the image, so thats what is in the database. No need to prefix it with the path again when deleting ?
Apr 13, 2023
6
Level 3
Existing Image is not getting deleted after uploading a new image
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
-------
if (request('image')) {
// delete the old image file
if (File::exists(public_path('backend/img/categories/main/' . $mainCat->image))) {
File::delete(public_path('backend/img/categories/main/' . $mainCat->image));
}
// save the new image file
$image = request()->file('image');
$img = rand() . '.' . $image->getClientOriginalExtension();
$location = public_path('backend/img/categories/main/' . $img);
$imageResize = Image::make($image);
$imageResize->fit(300, 300)->save($location);
// update the category record with the new image filename
$mainCat->image = $img;
}
$mainCat->save();
The image is saving but it cant for some reason read my old image and delete it to save new image rather its creating a new image leaving the old image in that folder. Did the same for destroy function and weirdly its working there.
Level 3
@Snapey Honestly even I don't know what is going on but these are the changes I made
public function update(Category $category)
{
$mainCat = $category;
$oldImage = $mainCat->image;
$mainCat->update($this->validateCategory($mainCat->id));
if (request()->hasFile('image')) {
//Delete the old image file
if (Storage::disk('mainCat')->exists($oldImage)) {
Storage::disk('mainCat')->delete($oldImage);
}
//Save the new image file
$image = request()->file('image');
$img = rand() . '.' . $image->getClientOriginalExtension();
$location = Storage::disk('mainCat')->path($img);
$imageResize = Image::make($image);
$imageResize->fit(300, 300)->save($location);
//Update the category record with the new image filename
$mainCat->image = $img;
}
$mainCat->slug = Str::slug(request('slug'));
$mainCat->save();
}
even if I put $oldImage after $mainCat->update it doesnt work.
Please or to participate in this conversation.