F
Filament5mo ago
CT

How to eager load within a select using Form Builder?

I have the following:
Forms\Components\Select::make('registrar_username_id')
->label('Registrar')
->relationship(name: 'registrarUsername', titleAttribute: 'username')
->getOptionLabelFromRecordUsing(fn(RegistrarUsername $record) => "{$record->registrar->name} -> {$record->username}")
->preload()
->searchable(),
Forms\Components\Select::make('registrar_username_id')
->label('Registrar')
->relationship(name: 'registrarUsername', titleAttribute: 'username')
->getOptionLabelFromRecordUsing(fn(RegistrarUsername $record) => "{$record->registrar->name} -> {$record->username}")
->preload()
->searchable(),
As you can see the call to $record->register->name is lazy loaded, which triggers an error for me because I am using Model::shouldBeStrict(). I realize that since it's an edit page there is no real benefit to eager loading, but I would like to keep strict mode active, but also remove this error. Perhaps there is some way to modify or access the query before the page is loaded? Anyone got any ideas?
5 Replies
Hass
Hass5mo ago
You can set in the model to always eagerLoad the relationship
Hass
Hass5mo ago
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Hass
Hass5mo ago
I’m not sure if this is the best way to handle this, maybe someone else have a better solution
awcodes
awcodes5mo ago
There’s a third option for ->relationship() that allows for modifying the query. Could probably apply eager loads there.
CT
CT5mo ago
ah yep, modifyQueryUsing on the relationship() call works perfectly.. thanks @awcodes !