Search code examples
laravelfilepondlaravel-filament

Laravel Model Event: delete() doesn't delete files fromstorage


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```


Solution

  • 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.