How to Delete File from Public Folder / Storage Folder in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Today, laravel delete file from storage folder is our main topic. In this article, we will implement a how to remove file from public folder in laravel. We will look at example of laravel delete file from public folder. this example will help you laravel remove file from public storage folder.

Sometime, we need to remove file from folder in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application. laravel store file in public folder and storage folder, so most of the cases you simply need to delete file from public folder or storage folder. here we will use File and Storage facade to removing files from folder in laravel application.

You can easily delete file from folder in laravel 5, laravel 6 and laravel 7 in this post solution. so let's see bellow example that will help to remove file from folder. first we will check file is exist or not then we remove it.

Example 1: Laravel Remove File from Public Folder using File Facade

Syntax:

File::delete(file_path);

Example:

In this example, i have one folder "upload" with test.png image in public folder. we will check first file is exist or not then we will remove it.

<?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.');

}

}

}

Example 2: Laravel Remove File from Storage Folder using Storage Facade

Syntax:

Storage::delete(file_path);

Example:

In this example, i have one folder "upload" with test.png image in public folder. we will check first file is exist or not then we will remove it.

<?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.');

}

}

}

I hope it can help you...

Tags :
Shares