Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
laravel
communitycreator

How to delete files using the Storage facade in Laravel

Chinweuba Elijah Azubuike

One way to delete a file from the public directory in Laravel is to use the Storage facade.

To delete a file, you will need to follow the following steps:

  • Step 1: Check to ensure that the folder and file exist.
  • Step 2: Delete the required file.

Code

The code below demonstrates the process of deleting a file from the public directory.

In this scenario, we have a folder called upload in the public directory. Within the upload folder, we have an image file called test.png.

<?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 files this way
                Storage::delete(['upload/test.png', 'upload/test2.png']);
            */
        }else{
            dd('File does not exist.');
        }
    }
}

?>

To delete the test.png file, the above code first ensures that the folder and file exist through the command Storage::exists('upload/test.png'). This ensures that upload/test.png is a valid path.

If the provided path is valid, we delete the file test.png through the command Storage::delete('upload/test.png');.

If the file does not exist, the else branch is chosen, and the 'File does not exist' message will be displayed.

RELATED TAGS

php
laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring