Laravel Delete Image or File From Public or Storage Folder

Hello Artisan,

In this example, I will explain how to delete files or images in Laravel from the public folder. I will show you two ways to delete files or images from the public folder. One is using File::delete() and other is @unlink() predefined function.

In this example, I will also show you the way to delete the previous image from the folder when updated by the new image in Laravel. If you don't know how to delete image from public folder in laravel 8 then this example is for you.

Example one to delete file from public:

public function delete()
{
    if( File::exists(public_path('file/example.jpg')) ) {
        Files::delete(public_path('file/example.jpg'));
    }
    return "File doesn't exists";
}

 

Example two to delete file from storage in Laravel:

public function deleteImage(Request $request)
{
        if(Storage::exists('upload/test.png')){
            Storage::delete('upload/test.png');
            /*
                Delete Multiple File like this way
                Storage::delete(['upload/example.png', 'upload/example2.png']);
            */
        }
    return 'File does not exists';

}

 

Now use this concept if you want to delete previous image from folder when updated by new image in laravel:

$currentPhoto = Upload::find($id)->photo;  //fecthing user current photo

if($request->photo != $currentPhoto){  //if not matched

    $userPhoto = public_path('img/profile/').$currentPhoto;

    if(file_exists($userPhoto)){

        @unlink($userPhoto); // then delete previous photo
        
    }
    
    //now insert new image
}

 

Read also: Laravel Vue JS CRUD Example With File Upload and Pagination

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js