Spread the love

File System are used to store the information and how to manage the structure, so to perform the file system based operations like Delete Folder Recursively With Files it uses Illuminate\Filesystem\Filesystem class in laravel. Laravel provides inbuilt library to access the file system and we can do multiple robust operations using the libraries. In this tutorial i will show you to make a directory in laravel and also i will show you to Delete Folder Recursively With File in using the library. If we perform same operations using the core php functions than it can be a hectic or lengthy code to implement but using the packages or library it will be easier to implement.

In this article I will use Illuminate\Filesystem\Filesystem class and File::deleteDirectory() method to delete the directory recursively in the folder. deleteDirectory Method accepts two parameters as below

File::deleteDirectory($path, $preserve)

Example Usage:

File::deleteDirectory(public("images/user/1");

Let’s understand Delete Folder Recursively With Files in Laravel with example step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Create controller

Let’s create a controller and add method performDeleteDirectory

php artisan make:controller FolderController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use File;
class FolderController extends Controller
{
    public function performDeleteDirectory(Request $request){
        
        if($request->folder_name!=''){
            $storageDestinationPath=storage_path('app/'.$request->folder_name);
         
            if (!File::exists( $storageDestinationPath)) {
                File::deleteDirectory($storageDestinationPath);
            }
            return response("Folder deleted successfully");
         }
  
      }
}

In above code First of all we are checking the directory is exist or not then if not available then we are creating the directory at the location.

If you want to delete from public directory then

$storageDestinationPath= public_path('app/'.$request->folder_name);

Step 3: Create two routes in routes/web.php

Create a route to create the directory

routes/web.php

<?php

use App\Http\Controllers\FolderController;
use Illuminate\Support\Facades\Route;

Route::get("/delete-directory",[FolderController::class,"performDeleteDirectory"]);

Leave a Reply