In this Laravel 12 tutorial, we’ll cover how to remove or delete files and images from both the public folder and the storage folder. The techniques shared here are compatible not only with Laravel 12 but also with older versions such as Laravel 6, 7, 8, 9, 10, and 11.
In many Laravel projects, file management is a common requirement. Whether you are handling image uploads, PDFs, or other documents, you’ll eventually need to delete files. Laravel provides multiple approaches to achieve this, depending on where the files are stored.
This guide will demonstrate how to use PHP’s unlink() function as well as Laravel’s File and Storage facades to efficiently delete files from public/ and storage/ directories.
Requirements:
- Laravel 12 project setup
- Understanding of file uploads
- Sample project with files inside public/uploads/ or storage/app/public/uploads/
Delete File from Public Folder
Example 1: Delete File Using File Facade
syntax
File::delete(File_PAth);
Before deletion, always check if the file exists at the given path. Also, make sure to import Illuminate\Support\Facades\File.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
class FileManagementController extends Controller
{
public function deleteFile()
{
if (File::exists(public_path('uploads/123.jpg'))) {
File::delete(public_path('uploads/123.jpg'));
return response()->json(['message' => 'File deleted successfully']);
}
}
}
The File facade in Laravel makes file deletion flexible and straightforward.
Deleting Multiple Files
You can delete one or more files by passing them as arguments:
File::delete($file1, $file2, $file3);
Deleting an Array of Files
$files = [$file1, $file2, $file3];
File::delete($files);
⚡ Key Points
- File::delete() won’t throw an error if the file is missing — it just skips it.
- To ensure a file exists before removing it, use File::exists($file).
Example 2: Using PHP unlink()
If you prefer plain PHP, you can use the unlink() function to directly delete files from the system.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileManagementController extends Controller
{
public function deleteFile()
{
$filePath = 'uploads/123.jpg';
if (file_exists(public_path($filePath))) {
$deleted = unlink($filePath);
if ($deleted) {
return response()->json(['message' => 'File deleted successfully']);
} else {
return response()->json(['message' => 'Unable to delete file'], 500);
}
}
}
}
Both the File facade and the native unlink() function can handle file deletion inside the public/ directory without any problem.
Read Also : Laravel 12 Image Validation Rules Example
Deleting Files from the Storage Folder
When your files are stored through Laravel’s storage system (e.g., in storage/app/public/), it’s recommended to use the Storage facade for removal.
Check out the full step-by-step guide here : Laravel 12 Delete File From Public / Storage Folder.
Top comments (0)