Media not available in the afterCreate lifecycle hook
Package
filament/spatie-laravel-media-library-plugin
Package Version
v3.2.97
Laravel Version
v11.19.0
Livewire Version
v3.5.4
PHP Version
PHP 8.2.22
Problem description
I have a form that accepts a PDF file upload (handled by the plugin). It also accepts a thumbnail image, but in case that is null the app generates a thumbnail from the first page of the PDF.
I've tried to hook into the afterCreate lifecycle hook of the creation process to check for that. What happens is no media is available on the record, even though in the database row is added.
public function afterCreate(): void
{
if (!$record->getFirstMedia('thumbnail')) {
$pdf = $record->getFirstMedia('pdf');
$thumbnailGenerator = app(GenerateThumbnailFromPdf::class);
$record->addMedia($thumbnailGenerator->generate($pdf))->withResponsiveImages()->toMediaCollection('thumbnail');
}
}
In this instance $pdf returns null. Note that I am not using database transactions.
Expected behavior
I would expect to already have media available here in this lifecycle hook.
Steps to reproduce
- Create a form with a SpatieMediaLibraryFileUpload component to upload the PDF (located
Forms\Components\SpatieMediaLibraryFileUpload::make('pdf')
->label('PDF File')
->collection('pdf')
- Hook into the lifecycle with
afterCreatemethod:
public function afterCreate() {
$pdf = $this->record->getFirstMedia('pdf');
dd($pdf);
}
$pdf should be an instance of Media here.
Reproduction repository (issue will be closed if this is not valid)
https://github.com/slovenianGooner/filament-issue-demo
Relevant log output
No response
Donate 💰 to fund this issue
- You can donate funding to this issue. We receive the money once the issue is completed & confirmed by you.
- 100% of the funding will be distributed between the Filament core team to run all aspects of the project.
- Thank you in advance for helping us make maintenance sustainable!
@slovenianGooner you may refresh model to access media
public function afterCreate() {
$this->record->refresh();
$pdf = $this->record->getFirstMedia('pdf');
}
Thanks @yogesh16