Last updated on February 17, 2023
In Laravel, the delete() method from the Storage class deletes the file. It accepts both string and array in the parameter. This means you can pass a single file name with the string data type to delete it, in case multiple files need to be deleted then pass the array with the files name.
To delete a file, first, you need to import the Storage class into your controller.
use Illuminate\Support\Facades\Storage;
Then you can use the Storage class’ delete() method with the file name to delete it.
public function deleteFile()
{
Storage::delete('file-name.jpg');
}
This deleteFile()
method simply deletes the file from storage/app/file-name.jpg
In case the file is in the child directory then you need to mention the folder name as well.
public function deleteFile()
{
Storage::delete('uploads/file-name.jpg');
}
The better way is to check the file if it exists before delete.
public function deleteFile()
{
// stored filename and path into variable
$fileNameWithPath = 'uploads/file-name.jpg';
// delete file if it exists
if (Storage::exists($fileNameWithPath)) {
Storage::delete($fileNameWithPath);
}else{
dd("Sorry, File doesn't exist.");
}
}