Laravel how to delete a file from Storage

Learn how to delete files from Laravel's storage with an example.

Deleting a File from Storage

In Laravel, deleting a file from Storage is a pretty straight-forward process. All that you need to do is use the Storage facade and the delete method. This method will delete the file from the specified disk.

For example, if you are using the local driver and have a file at storage/app/file.txt, you can delete it by using the following syntax:

Storage::delete('file.txt');

If you are using the s3 driver, you could use the following syntax:

Storage::disk('s3')->delete('file.txt');

In addition to deleting a single file, you may also delete an array of files from Storage. For example, if you have files at storage/app/file1.txt, storage/app/file2.txt, and storage/app/file3.txt, you may delete them all using the following syntax:

Storage::delete([
    'file1.txt',
    'file2.txt',
    'file3.txt',
]);

If you need to delete a directory of files, you may use the directory method before calling the delete method. For example, if you have a directory of files at storage/app/files, you may delete them all using the following syntax:

Storage::deleteDirectory('files');

Finally, if you need to delete a file only if it exists, you may use the delete method's exists parameter. This parameter will check to see if a file exists before attempting to delete it. For example, if you have a file at storage/app/file.txt, you can delete it only if it exists by using the following syntax:

Storage::delete('file.txt', $exists = true);

That's all there is to deleting files from storage in Laravel. With the Storage facade and the delete method, you can easily delete any file or directory of files. Happy coding!

Answers (0)