Milind Daraniya

How to remove image / file from from storage in Laravel 10

Published July 23rd, 2023 3 min read

In Laravel 10, removing images or files from storage is a common requirement when building applications. Whether you need to delete user-uploaded files, remove outdated images, or implement a file cleanup mechanism, this guide will walk you through the process. We'll explore three examples to demonstrate different approaches for file removal. Let's get started!

Prerequisites Before diving into the examples, ensure that you have the following prerequisites:

  • Laravel 10 installed on your local development environment
  • Basic understanding of Laravel file storage concepts

Example 1: Deleting a Single File In this example, we'll cover the basics of removing a single file from storage. Follow these steps:

  1. Determine the file path you wish to delete.
  2. Use the Storage facade in Laravel to delete the file. Here's an example:
use Illuminate\Support\Facades\Storage;

$file = 'path/to/file.jpg'; // Replace with the actual file path

if (Storage::exists($file)) {
    Storage::delete($file);
    return "File deleted successfully!";
} else {
    return "File does not exist.";
}

Example 2: Deleting Multiple Files If you need to remove multiple files at once, you can make use of the Storage::delete() method by passing an array of file paths. Here's an example:

use Illuminate\Support\Facades\Storage;

$files = [
    'path/to/file1.jpg',
    'path/to/file2.jpg',
    'path/to/file3.jpg',
];

$deletedFiles = [];

foreach ($files as $file) {
    if (Storage::exists($file)) {
        Storage::delete($file);
        $deletedFiles[] = $file;
    }
}

return "Files deleted successfully: " . implode(', ', $deletedFiles);

Example 3: Deleting Files Using Wildcard Patterns If you have a set of files matching a specific pattern or wildcard, you can use the Storage::delete() method with the glob() function to find and delete them. Here's an example:

use Illuminate\Support\Facades\Storage;

$pattern = 'path/to/files/*.jpg'; // Replace with the actual wildcard pattern

$files = glob(storage_path('app/public/' . $pattern));

foreach ($files as $file) {
    Storage::delete($file);
}

return "Files matching the pattern '{$pattern}' have been deleted.";

Note: Ensure that you have the necessary permissions to delete files in the storage directory.

Remember to exercise caution when deleting files and validate user permissions if required.

Happy coding! 🎉