How to delete a directory from the public path in Laravel
Overview
Deleting a directory from your application can be very useful in cases where you deleted a user account and you want the corresponding files to be deleted as well.
The deleteDirectory() method is used to carry out this very important function. So in this shot, we will learn how to do this in a simple way.
Syntax
Storage::deleteDirectory(public_path('path/to/folder'));
Parameters
The deleteDirectory() method receives one parameter which is the path to the directory you want to delete.
Note: Don’t forget to import the
Storagefacade to your control while using it.
Example
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
class FrontendController extends Controller
{
public function deleteFolder()
{
Storage::deleteDirectory(public_path('path/to/folder'));//deleting directory using the storage facade
}
}
In this example, we have create a deleteFolder() function where we call the deleteDirectory() method on the Storage facade. The public_path('path/to/folder') method, passed as a parameter, provides the path of the folder to be deleted.
Methods explained
-
The
deleteDirectory()is a method that accepts the path of the directory and deletes it. -
The
public_path()is a method Laravel uses to fetch the folder passed as a parameter to the path of the directory. -
The
Storagefacade grants access to the file system of the application so that thedeleteDirectory()method can delete the specified directory.
Exceptions
The Storage::deleteDirectory(public_path('path/to/folder')); will throw an error if the directory is not found.