To ensure that the related data is pre-selected in a Select
field in Laravel Filament you need to set the value of the field to the data from the model that you’re editing.
Since you are using a hasMany
relationship the issue is that Select::make
is expecting a single value or an array of values but you’re working with a collection of related models.
In your case since the relationship is hasMany
you can retrieve the related data from the AddOn.php
model and pass it as the value to the Select
field.
Look at this code
First modify the Select
field to pre-select related values
// In the AddOnResource
Select::make('vehicle_type')
->multiple()
->label('Vehicle Type')
->options(function () {
return \App\Models\VehicleType::pluck('name', 'id');
})
->searchable()
->placeholder('Vehicle Type')
->required()
->default(function ($record) {
return $record->addOnVehicleType->pluck('vehicle_type_id')->toArray();
}),
then update the relationship method on the model like this
public function addOnVehicleType() {
return $this->hasMany(AddOnVehicleType::class);
}
The AddOnVehicleType
table must have the appropriate foreign keys to store the relation hasMany
. Save the selected vehicle_type
correctly when updating the AddOn.php
resource 👋