0
0
LaravelHow-ToBeginner · 3 min read

How to Delete a File in Laravel: Simple Guide

In Laravel, you can delete a file using the Storage::delete('path/to/file') method from the Storage facade or the native PHP unlink() function. The Storage method works with files stored in Laravel's configured disks like local or cloud storage.
📐

Syntax

The main way to delete a file in Laravel is using the Storage::delete() method. It takes the file path as a string and returns true if the file was deleted successfully or false otherwise.

Alternatively, you can use PHP's native unlink() function by providing the full file path.

php
use Illuminate\Support\Facades\Storage;

// Delete file using Laravel Storage facade
Storage::delete('folder/filename.ext');

// Delete file using PHP unlink function
unlink(storage_path('app/folder/filename.ext'));
💻

Example

This example shows how to delete a file named example.txt stored in the default local disk using Laravel's Storage facade. It checks if the file exists before deleting and prints a success or failure message.

php
<?php

use Illuminate\Support\Facades\Storage;

$filePath = 'files/example.txt';

if (Storage::exists($filePath)) {
    $deleted = Storage::delete($filePath);
    if ($deleted) {
        echo 'File deleted successfully.';
    } else {
        echo 'Failed to delete the file.';
    }
} else {
    echo 'File does not exist.';
}
Output
File deleted successfully.
⚠️

Common Pitfalls

  • Trying to delete a file without checking if it exists can cause errors or unexpected behavior.
  • Using incorrect file paths or missing disk configuration leads to failure in deleting files.
  • For files outside Laravel's storage disks, unlink() requires the full absolute path.
  • Permissions issues on the server can prevent file deletion.
php
<?php

// Wrong: Deleting without checking existence
Storage::delete('files/missing.txt'); // May return false silently

// Right: Check existence before deleting
if (Storage::exists('files/missing.txt')) {
    Storage::delete('files/missing.txt');
}
📊

Quick Reference

MethodDescriptionUsage Example
Storage::delete()Deletes a file from configured diskStorage::delete('path/to/file.txt');
Storage::exists()Checks if a file existsStorage::exists('path/to/file.txt');
unlink()Native PHP function to delete file by absolute pathunlink(storage_path('app/path/to/file.txt'));

Key Takeaways

Use Laravel's Storage facade for deleting files within configured disks for better abstraction.
Always check if the file exists before attempting to delete it to avoid errors.
Use the full absolute path with PHP's unlink() for files outside Laravel storage.
Ensure proper file permissions to allow deletion on the server.
Storage::delete() returns true if deletion succeeds, false otherwise.