Filament Multi-Select Not Loading Default Values from Third Table (Not Pivot Table)

Hi all, I'm facing an issue with Filament in Laravel where a multi-select field isn't loading its default values in the edit form. My setup involves saving selected values in a third table, which isn't a traditional pivot table but rather an additional table (CarUsageRecord) related to a Task model. The Problem When editing a record, the default function in Select::make doesn't run, so the previously selected values from the third table aren't loaded into the select field, making it impossible to see what was selected before. My Setup Task model: Has a one-to-many relationship with CarUsageRecord. CarUsageRecord model: Stores car_id and task_id to track which cars are linked to a task. Task model relationship:
public function carUsageRecords():
{
return $this->hasMany(CarUsageRecord::class);
}
public function carUsageRecords():
{
return $this->hasMany(CarUsageRecord::class);
}
Form setup in the Filament resource:
Select::make('car_id')
->relationship('car', 'license_plate')
->multiple()
->reactive()
->saveRelationshipsUsing(function ($component, $state) {
$record = $component->getRecord();
CarUsageRecord::where('task_id', $record->id)->delete();
foreach ($state as $carId) {
CarUsageRecord::create([
'car_id' => $carId,
'task_id' => $record->id,
]);
}
})
Select::make('car_id')
->relationship('car', 'license_plate')
->multiple()
->reactive()
->saveRelationshipsUsing(function ($component, $state) {
$record = $component->getRecord();
CarUsageRecord::where('task_id', $record->id)->delete();
foreach ($state as $carId) {
CarUsageRecord::create([
'car_id' => $carId,
'task_id' => $record->id,
]);
}
})
What I've Tried Attempted to use the default method to load selected car IDs, but it doesn’t run during form load. Used dump() and Log::info() for debugging inside the default method, but no output indicates the method is not executing. Saving works fine, but loading the values during edit is the issue. What I Need How can I ensure the default method runs during form load? What’s the best way to load values into a multi-select field from a third table? Any advice would be appreciated!
2 Replies
luciano.mizra
luciano.mizra4w ago
As far as I understand (I didn't check), If you are modifying the way it is saved, you should also modify the way you retrieve it. For that, you have: getSearchResultsUsing()
Tommika79
Tommika794w ago
Thanks for the idea. This is how it was solved:
->afterStateHydrated(function ($component, $state) {
$record = $component->getRecord();
if ($record && $record->exists) {
$state = $record->carUsageRecords->pluck('car_id')->toArray();
$component->state($state);
}
})
->afterStateHydrated(function ($component, $state) {
$record = $component->getRecord();
if ($record && $record->exists) {
$state = $record->carUsageRecords->pluck('car_id')->toArray();
$component->state($state);
}
})
Want results from more Discord servers?
Add your server