How To Delete File From Public Folder In Laravel 10

Deleting a file from the public folder in Laravel can be accomplished using various approaches, but here’s some best example of how to delete file from public folder in laravel 9 or 10.

Using Laravel File System and using core php function file_exists() and unlink(), Commonly, Laravel file is located in the public folder. You can easily remove/delete/unlink file from your public or storage directory in laravel.

Please note that the code provided is a guideline and may need adjustments based on your specific requirements.

  1. Locate the file you want to delete within the public folder.
  2. Determine the path to the file, relative to the public folder.

Example 1: Using File System

Add the File Facades at the top of the controller and update the code something like this.

use Illuminate\Support\Facades\File;
public function removeFile()
{  
  
  $filePath = "/uploads/filename.jpeg"; 
  if(File::exists($filePath)) {
    File::delete($filePath);
  } else {
  dd('File does not exists.');
  }
}

Example 2: Using Storage System

You can use the Storage prebuild method of laravel to delete file from public or storage folder easily.

public function deleteImage()
{  

  $imagePath = "/uploads/imagename.txt"; 
  if(Storage::exists($imagePath)){
    Storage::delete($imagePath);
  } else{
   dd('Image does not exists.');
  }
}

Example 3: Using Core PHP functions

Either use the laravel methods you can use the php function as well to remove file from public directory.

public function removeImage()
{  

    $filePath = "/uploads/filename.ext"; 
    if(file_exists(public_path($filePath))){
      unlink(public_path($filePath));
    } else {
      dd('File does not exists.');
    }

}

Example 4: One more best example to delete

Here a best example you can use to delete file from public directory in your laravel application.

public function removeFile()
{
    if(file_exists('file_path')){
        @unlink('file_path');
    }
    parent::delete();
}

I hope these examples help to remove/delete files from public folder in laravel.

Leave a Comment