Laravel 8 – How to delete a file from the public storage folder

In this tutorial, we will learn how we can delete a file from the public storage folder in Laravel.

In web development, when we delete the data we only need to delete it from the database. But in the case of medial files like images and other types of files, when we delete the file record from the database then we also need to delete it from the disk.

Most beginners in web development do, they only delete the record data from the database not the file from disk. In this case, your disk consumes space and if your hosting space is limited then over time it could create a problem of storage. So it is always advised to delete the file from the disk when you have to remove the file record from the database.

And in Laravel PHP, It is very easy to check if a file exists on a given location and delete it from the given path, You can use File Facade or Storage Facade to delete files.

Remove file using File Facade

File::delete(file_path);

It is good practice to check if a file exists before deleting it. Then the chances of getting errors become less. So you can make the check of the file exist before deleting it. Below is an example of the same.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use File;
  
class DemoController extends Controller
{
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    public function removeImage(Request $request)
    {
        if(File::exists(public_path('upload/test.png'))){
            File::delete(public_path('upload/test.png'));
        }else{
            dd('File does not exists.');
        }
    }
}

Remove file using Storage Facade

Storage::delete(file_path);

The same file check can be performed with the storage facades. Below is an example of the same.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Storage;
  
class DemoController extends Controller
{
    /**
     * Write code on Construct
     *
     * @return \Illuminate\Http\Response
     */  
    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/test.png', 'upload/test2.png']);
            */
        }else{
            dd('File does not exists.');
        }
    }
}

Hope you liked the article and it helped you to solve your query. You can find the below-related post on this topic for more information.

Recommended Posts For You