How do you delete a PDF file from storage after the Edit.(only changing the FileUpload)
I am able to replace a pdf file on edit but the previous one does not get removed from Storage. How do i handle this so as to not store unused files.
Solution:Jump to solution
I would handle this in an observer where you can check the old state of the file against the new state of the file and only delete if they don’t match.
4 Replies
You can customize the edit action, so after updating you can delete old storage file
https://filamentphp.com/docs/3.x/actions/prebuilt-actions/edit#lifecycle-hooks
So how do you do that specifically so that when you do an edit, you don't make a deletion and you've altered a different field on the form and saved.
->schema([
Section::make([
Select::make('legislation_id')
->required()
->label('Legislation')
->relationship('legislation', 'title'),
Forms\Components\FileUpload::make('pdf')
->required()
->openable()
->downloadable()
->directory('legislation')
->helperText('Upload a PDF file, ensure no two files have similar names to avoid loss of files!')
->preserveFilenames()
->acceptedFileTypes(['application/pdf'])
->label('PDF'),
Forms\Components\DatePicker::make('date')
->required(),
Select::make('status')
->required()
->options(PdfStatus::class)
]),
]);
}
Solution
I would handle this in an observer where you can check the old state of the file against the new state of the file and only delete if they don’t match.
This worked, thanks!
public function updated(LegislationPdf $legislationPdf): void
{
if ($legislationPdf->isDirty('pdf')) {
Storage::disk('public')->delete($legislationPdf->getOriginal('pdf'));
}
}