F
Filament16mo ago
justgkp

Is there any way to delete old image/attachments when deleting or updating records??

I tried different ways to delete old image path but no solutions were working. In fact filament tricks as well has a third party function that too didn't work. Can anyone help to achieve this.
5 Replies
devhammed
devhammed16mo ago
@justgkp I typically use a File model for attaching things like images to models since it will allow me to store extra metadata like width, height, duration (for videos), page numbers (PDF) etc. But what matters is that you can call the "using" method on Edit action which allows you to customize the update process, this will also give you the ability to check if there is a previous image and delete it after attaching the new one to the model. Note that the uploaded file property will be the path string as it would have been saved already according to what you have configured. And it will be null if the file has been detached in the form so you can also delete the previous image file in that case to persist the removal. Below is an example code from one of the projects I have worked on:
Tables\Actions\EditAction::make()->using(
function (Product $record, array $data): Product {
$previousImage = $record->image;
$imagePath = $data['image'] ?? null;

$record->update(
collect($data)->except('image')->toArray(),
);

if ($imagePath === null) {
$previousImage?->delete();
}

if (is_string($imagePath) && $previousImage?->path !== $imagePath) {
$image = File::fromFileSystem($imagePath, $previousImage?->disk ?? 'public');

$record->image()->save($image);

$previousImage?->delete();
}

return $record;
},
),
Tables\Actions\EditAction::make()->using(
function (Product $record, array $data): Product {
$previousImage = $record->image;
$imagePath = $data['image'] ?? null;

$record->update(
collect($data)->except('image')->toArray(),
);

if ($imagePath === null) {
$previousImage?->delete();
}

if (is_string($imagePath) && $previousImage?->path !== $imagePath) {
$image = File::fromFileSystem($imagePath, $previousImage?->disk ?? 'public');

$record->image()->save($image);

$previousImage?->delete();
}

return $record;
},
),
justgkp
justgkpOP16mo ago
Image updating but old image not detached.
devhammed
devhammed16mo ago
Detached as in?
justgkp
justgkpOP16mo ago
Thanks for your support as well.
Want results from more Discord servers?
Add your server