How to handle the deleteAction for the file-upload field

I'm looking to ensure that when the user deletes a file attached to a posting, that the corresponding uploaded file is also removed. There doesn't seem to be anything in the documentation on this, and chatGPT is hallucinating with an incorrect method that does not exist. I am handling deleting the associated files when the post is deleted by overriding the boot/deleted method, but am unclear on how to handle it at just the file level.
2 Replies
charlie
charlie2d ago
It is the responsibility of the developer to delete these files from the disk if they are removed, as Filament is unaware if they are depended on elsewhere. One way to do this automatically is observing a model event.
From the docs here: https://filamentphp.com/docs/3.x/forms/fields/file-upload#configuring-the-storage-disk-and-directory Here is how you could do it in a table for example:
Tables\Actions\DeleteAction::make()
->after(function (YourModel $record) {
if ($record->path) {
$deleted = Storage::disk('local')->delete($record->path);
if (!$deleted) {
Notification::make()
->title('Error')
->body('An error happened when deleting the file')
->danger()
->send();
}
}
})
Tables\Actions\DeleteAction::make()
->after(function (YourModel $record) {
if ($record->path) {
$deleted = Storage::disk('local')->delete($record->path);
if (!$deleted) {
Notification::make()
->title('Error')
->body('An error happened when deleting the file')
->danger()
->send();
}
}
})
islandnuge
islandnugeOP2d ago
Thank you!

Did you find this page helpful?