Laravel Storage Delete File If Exists Example

By Hardik Savani November 5, 2023 Category : Laravel

Hello Artisan,

In this short tutorial, we will share the quick and straightforward way to laravel storage delete file if exists. This example will help you laravel delete file from storage public. you'll learn how to delete file in laravel. This article will give you a simple example of how to delete file in storage laravel 10.

Laravel Storage facade provides exists() to check file is exists or not and delete() method to remove files from storage folder. so, let's see the simple example code.

let's see the example:

Example 1: Laravel Storage Delete File If Exists

here is a controller code of delete file using Storage facade.

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

if(Storage::exists('upload/test.txt')){

Storage::delete('upload/test.txt');

dd('File deleted successfully.');

}else{

dd('File does not exist.');

}

}

}

Output:

File deleted successfully.

Example 2: Laravel Storage Delete Multiple Files

here is a controller code of delete multiple files using Storage facade.

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

Storage::delete(['upload/test.txt', 'upload/test2.txt', 'upload/test3.txt']);

dd('Files deleted successfully.');

}

}

Output:

Files deleted successfully.

I hope it can help you...

Tags :
Shares