Deleting files helps you remove unwanted or old files from your storage to keep things clean and save space.
0
0
Deleting files in Laravel
Introduction
When a user deletes a profile picture and you want to remove it from the server.
When cleaning up temporary files after processing uploads.
When removing old logs or backups automatically.
When deleting files related to a deleted database record.
When freeing up storage space by removing unused files.
Syntax
Laravel
use Illuminate\Support\Facades\Storage;
Storage::delete('path/to/file.jpg');Use the Storage facade to work with files in Laravel's storage system.
The path is relative to the storage disk you are using (default is 'app' folder).
Examples
Deletes a single file named
image1.jpg inside the photos folder.Laravel
Storage::delete('photos/image1.jpg');Deletes multiple files at once by passing an array of file paths.
Laravel
Storage::delete(['photos/image1.jpg', 'photos/image2.jpg']);
Checks if the file exists before deleting it to avoid errors.
Laravel
if (Storage::exists('docs/manual.pdf')) { Storage::delete('docs/manual.pdf'); }
Sample Program
This controller method deletes a file from the uploads folder based on the filename sent in the request. It first checks if the file exists to avoid errors, then deletes it and returns a success message. If the file is not found, it returns a 404 error message.
Laravel
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Storage; use Illuminate\Http\Request; class FileController extends Controller { public function deleteFile(Request $request) { $filePath = 'uploads/' . $request->input('filename'); if (Storage::exists($filePath)) { Storage::delete($filePath); return response()->json(['message' => 'File deleted successfully.']); } else { return response()->json(['message' => 'File not found.'], 404); } } }
OutputSuccess
Important Notes
Always check if a file exists before deleting to prevent errors.
Laravel's Storage facade works with different disks like local, s3, etc. Make sure you use the correct disk if not default.
Deleting a file is permanent, so be careful when deleting user files.
Summary
Use Storage::delete() to remove files in Laravel.
You can delete one or many files by passing a string or array.
Check if files exist before deleting to avoid errors.