How to delete old uploaded image when update Laravel?

We have learnt in previous tutorials on how to upload single and multiple in Laravel. Let’s now learn about image updates. When we update an image, we should delete old uploaded image to save application memory and ensure two separate images coinciding with similar names.

Let’s go over an example of “How to delete old uploaded image from the folder when updated by a new image in Laravel”. You can easily apply these steps in your Laravel 5, Laravel 6, Laravel 7, Laravel 8, and Laravel 9 applications.

Step 1: Edit Image on Frontend

You can add the “Edit Image” option to the view blade that we already created in the upload image tutorial. This comes next to the “Add/Upload Image” option we already created.

Step 2: Update Route

We had already created a new route for image uploads. Now we should append in it another route for update or edit image. The new code snipper will be as shown below.

Route::get('image-upload', [ UploadImageController ::class, 'uploadImage' ])->name('image.upload');
Route::post('image-upload', [ UploadImageController ::class, 'uploadImagePost' ])->name('image.upload.post');
Route::get('image-upload{id}', [UploadImageController ::class, 'editProduct'])->name('image.edit');

Step 3: Update Controller

To make the new route and edit button on blade work. You will now create a new method in the Controller class we already created in the upload image tutorial.

This performs the main method to delete old uploaded image and replace with the new one. The function will have the code snippet as shown below.

if($request->hasFile('file_name')) { 
    $name = strtolower($request->file('file_name')->getClientOriginalName());
    $file_name = time().'_'.$name;
    $path = $request->file('file_name')->storeAs('public/uploads',$file_name);
    $model->file_name = $file_name;
    $Image = str_replace('/storage', '', $request->old_image);

    #Using file
    if( File::exists(public_path('uploads/' . $Image)) ) {
        Files::delete(public_path('uploads/' . $Image));
    }

    #Using storage
    if(Storage::exists('uploads/' . $Image)){
        Storage::delete('/public/uploads/' . $Image);
    }
} else {
    $model->file_name = $request->file_name_old;
}

Leave a Comment