SpatieMediaLibraryUpload replace file in collection

SpatieMediaLibraryFileUpload::make('check_overlay')
->hiddenLabel()
->formatStateUsing(fn () => null)
->label('Background Image')
->disk('s3')
->collection('check_overlay')
SpatieMediaLibraryFileUpload::make('check_overlay')
->hiddenLabel()
->formatStateUsing(fn () => null)
->label('Background Image')
->disk('s3')
->collection('check_overlay')
. I am surprised this isnt documented, but I am having a hard time trying to figure out how to upload a new image and only have one image in that collection for that model record. Right now it just keeps adding new ones. Ive tried a few different options with ->saveRelationshipsUsing(), but couldnt get it to delete the other records first. Am i missing something simple? Do i need to create a special relationship on the resource model this form is part of?
4 Replies
Mark Chaney
Mark Chaney6mo ago
Anyone? I’m sure I’m missing something simple here as it seems like a pretty standard need
wyn
wyn6mo ago
Maybe you can create a new form which inherits SpatieMediaLibraryFileUpload and override that method i used Forms\Components\Section::make('Images') ->schema([ FileUpload::make('media') ->preserveFilenames() ->disk('s3') ->imageEditorAspectRatios([ null, '16:9', '4:3', '1:1', ]) ->imageEditor() ->multiple() ->visibility('private') ->maxFiles(5) ]) ->collapsible() and in createProduct which is app/Filament/Resources/Shop/ProductResource/Pages/CreateProduct.php protected function handleRecordCreation(array $data): Model { $productModel = parent::handleRecordCreation($data); if (isset($data['media'])) { $mediaPath = $data['media']; if (is_array($mediaPath)) { foreach ($mediaPath as $path) { $productModel->addMediaFromDisk($path, 's3')->toMediaCollection('products'); } } } return $productModel; } }
DrByte
DrByte6mo ago
I think if you just declare your media collection correctly on the model as single() it will be enough. See: https://spatie.be/docs/laravel-medialibrary/v11/working-with-media-collections/defining-media-collections
Mark Chaney
Mark Chaney6mo ago
Thanks! I will definitely try that out. Makes sense. I really appreciate it