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
awcodes
awcodes4d ago
Nothing specific in filament. The best place to do that would be an observer on the model.
TranceCode
TranceCodeOP4d ago
i try with this example, but is not working!
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make()
->after(function (Business $record) {
//Delete logo
if($record->logo) {
Storage::disk('public')->delete($record->logo);
}
//Eliminar imágenes adicionales si existen (ejecutando eliminación con el array)
if(is_array($record->images)) {
foreach($record->images as $image) {
Storage::disk('public')->delete($image);
}
}
})
])
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make()
->after(function (Business $record) {
//Delete logo
if($record->logo) {
Storage::disk('public')->delete($record->logo);
}
//Eliminar imágenes adicionales si existen (ejecutando eliminación con el array)
if(is_array($record->images)) {
foreach($record->images as $image) {
Storage::disk('public')->delete($image);
}
}
})
])
awcodes
awcodes4d ago
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.
Bruno Pereira
Bruno Pereira4d ago
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?
Bruno Pereira
Bruno Pereira4d ago
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.
ChesterS
ChesterS4d ago
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 you
Bruno Pereira
Bruno Pereira4d ago
It's up to OP to decide. I just added a possible solution based on the code he provided.
ChesterS
ChesterS4d ago
Oh shit sorry, I thought you were the OP 😂
toeknee
toeknee4d ago
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
Bruno Pereira
Bruno Pereira4d ago
No prob 👍🏻

Did you find this page helpful?