How To Delete File From Public Folder In Laravel 9

Morris Muriuki Muthigani
80
0
laravel

02/09/2023 (1 year ago)


In this article, we will see how to delete files from the public folder in laravel 9. Here, we will learn how to delete or remove files and images from the public and storage folder in laravel 8 and laravel 9. In laravel, you can store files as per your requirement in a public folder and storage folder.

So, let's see how to delete files from the storage folder in laravel 9, laravel 9 delete files, laravel 8/9 delete files from storage, unlink files in laravel 9,  how to delete image from the public folder in laravel 9, and how to delete file in laravel 9.

Example:

Add the File Facades at the top of the controller.

use Illuminate\Support\Facades\File;

Laravel Syntax:

File::delete(file_path);

Delete Multiple Files:

File::delete([
  '$file1',
  '$file2',
  '$file3'
]);

The delete method accepts a single filename or an array of files to delete.

use Illuminate\Support\Facades\Storage;
 
Storage::delete('file.jpg');
 
Storage::delete(['file.jpg', 'file2.jpg']);

If necessary, you may specify the disk that the file should be deleted.

use Illuminate\Support\Facades\Storage;
 
Storage::disk('s3')->delete('path/file.jpg');

 

Example: Using Storage System

In this example, we delete images using the laravel Storage function in the storage folder. 

public function removeImage()
{  
  if(\Storage::exists('upload/img1.png')){
    \Storage::delete('upload/img1.png');
  }else{
    dd('File not found.');
  }
}

 

Example: Using File System

Now, we are deleting images using the laravel File function from the public folder.

public function removeImage()
{  
  if(\File::exists(public_path('upload/img1.png'))){
    \File::delete(public_path('upload/img1.png'));
  }else{
    dd('File not found');
  }
}

 

Example: Using PHP

In PHP, we check file is exist or not then unlink the file path using the unlink() PHP function.

public function removeImage()
{  
    if(file_exists(public_path('upload/img1.png'))){
      unlink(public_path('upload/img1.png'));
    }else{
      dd('File not found');
    }
}

Discussion (0)

Recent Blogs

Our Recent Blogs