How to delete a directory with files using Laravel

Deleting a directory with files in Laravel involves recursively deleting all the files and subdirectories within the directory. Here’s an example that demonstrates how to delete a directory with files using Laravel. Please note that the code provided is a guideline and may require adjustments based on your specific requirements.

Here an example you can follow how to delete public or storage folder with all files in laravel application.

Example 1: Using Laravel File System

Here the file system use to delete the directory with files in laravel.

Ensure that you have the necessary use statement at the top of your file to import the File facade.

use Illuminate\Support\Facades\File; 

public function deleteFolder() 

Example 2: Using Laravel Storage System

Second, we use Storage::deleteDirectory to delete a folder that is in your storage directory.

public function removeFolder()
    $response = Storage::deleteDirectory('folder/path');

Remember to use caution when deleting directories and files, as this action cannot be undone. Test your code thoroughly and make sure you have backups of any important data before executing such operations.

1 thought on “How to delete a directory with files using Laravel”

Leave a Comment