How to delete image or images when deleting a record?
When I delete a record that has images and I save the images in a folder and the paths in the table, deleting a record deletes everything from the database, but the images still exist in the folder, how should these images be deleted? Is there anything that Filament has preconfigured already?
Thank you so much!
10 Replies
Nothing specific in filament. The best place to do that would be an observer on the model.
i try with this example, but is not working!
Can you dd $record in after? Does it still exist at this point in the lifecycle?
Not sure, but that’s usually why a model observer might be better.
shouldn't be before instead of after? Because it's after the record deletion, which means the record is already deleted, or filament keeps it in cache?
https://filamentphp.com/docs/3.x/actions/prebuilt-actions/delete#lifecycle-hooks
I think you need to use the before. Delete the files before deleting the record from database.
as awcodes said above, it's better if you do it in an observer or delete them manually.
before
runs before the delete actually happens. so if something goes wrong and the record doesn't get deleted, you'll have deleted the files already. Anyway, up to youIt's up to OP to decide. I just added a possible solution based on the code he provided.
Oh shit sorry, I thought you were the OP 😂
So $record will be returned as expected in the after but any relationship data etc won't because the record no longer exist at this point you are just getting the object
So you need to find the images and then remove them
No prob 👍🏻