#Image not deleting my existing image and save new image

9 messages · Page 1 of 1 (latest)

thorny kernel
#
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
-------
if (request('image')) {
    // delete the old image file
    if (File::exists('backend/img/categories/main/' . $mainCat->image)) {
        File::delete('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.

pale vale
#

Just try a File::delete and put the file name manually to try.

#

The path like that backend/img/categories/main/' . $mainCat->image must be incorrect, why don't use public_path as you did for $location ?

#

I'd even suggest to create a disk in filesystem. 👍

thorny kernel
#

hmm ok I am gonna make the changes as you suggested, will let you know the result

thorny kernel
#

@pale vale I did what you said created a filesystem

'images' => [
   'driver' => 'local',
   'root' => public_path('backend/img/categories/main/'),
   'url' => env('APP_URL') . '/backend/img/categories/main/',
],

the in my function

if (Storage::exists('images/main/' . $mainCat->image)) {
    Storage::delete('images/main/' . $mainCat->image);
}

Same result cant find the existing image to delete rather upload a new image

pale vale
#
\Illuminate\Support\Facades\Log::debug(print_r(Storage::disk('yourDisk')->path('/yourPath'), true));
thorny kernel
#

apparently I had to keep $main->image in a variable first to make it work