Home > Software design >  Laravel Model Event: delete() doesn't delete files fromstorage
Laravel Model Event: delete() doesn't delete files fromstorage

Time:01-04

I am using FilePond for the image upload. It generates random strings for the images uploaded and is saved in database as Array.

I tried to do the following, it deletes the record but doesn't delete the files associated with it.

Since it's an array, I tried this:

foreach($this->attachments as $attachment) {
            if(File::exists(storage_path($attachment))) {
                Storage::delete($attachment);
            }
        }

Also tried this:

if(Storage::exists($this->attachments))
{
  Storage::delete($this->attachments);
}

Note: I am using Filament as the admin dashboard.

The files are being saved at storage/app/public/vehicle-images

I did php artisan storage:link, so the public folder shows ``public/storage/vehicle-images```

CodePudding user response:

In this example, the file exists in: Laravel/storage/app/public/vehicle-images

$filename = 'test.txt';

if(\File::exists(storage_path('app/public/vehicle-images/'.$filename))){
   \File::delete(storage_path('app/public/vehicle-images/'.$filename));
}

To better understand where the files are, and after that you can simply foreach loop check/delete.

You can read more on this here: https://laravel.com/docs/9.x/filesystem#the-public-disk

You can also later on specify a disk for that folder to make things easier to access.

Finally:

foreach($this->attachments as $attachment) {

    //Option #1: if $attachment == file.txt
    //use this code:
    if(\File::exists(storage_path('app/public/vehicle-images/'.$attachment))){
       \File::delete(storage_path('app/public/vehicle-images/'.$attachment));
    }
    
    //Option #2: if $attachment == vehicle-images/file.txt
    //use this code:
    if(\File::exists(storage_path('app/public/'.$attachment))){
       \File::delete(storage_path('app/public/'.$attachment));
    }

}

If you can show me how the filePond array looks like, I can adjust the code to work with it.

CodePudding user response:

I got it. FilePond doesn't only store the image name, it also stores the url/folder the image was saved in. So instead of image.png, it is vehicle-images/image.png.

The code should be:

File::exists('storage/' . $attachment)

Which will read as: storage/ vehicle-images/image.png.

Working code block:

foreach ($this->attachments as $attachment) {
            if (File::exists('storage/' . $attachment)) {
                File::delete('storage/' . $attachment);
            }
        }
  • Related