pivot-tablelaravel-filamentfilamentphp

Filament CheckListbox - Extra Pivot table data


How can I return the amenity_type_id from my Amenity model, as the CheckBoxList uses by default the pluck() method and I'm not sure how to get fields id, name, as well as amenity_type_id so it can be saved to the pivot table amenity_property.

amenity_property table consists of: amenity_id, property_id, amenity_type_id

$record->amenity_type_id value always is null because it's not available in the collection.

$options = Amenity::all()->pluck('name', 'id');

CheckboxList::make('amenities')
    ->label('Amenities')
    ->columnSpanFull()
    ->relationship('amenities', 'name')
    ->options($options)
    ->pivotData(function ($record) {
        return [
            'amenity_type_id' => $record->amenity_type_id,
        ];
    })
    ->columns(3),

Looking for recommendations for this situation. Thanks!


Solution

  • To include amenity_type_id in the pivot table, you need to adjust the way you prepare your options and handle the pivot data

    First don't use pluck instand use mapWithKeys

    $options = Amenity::all()->mapWithKeys(function ($item) {
        return [$item->id => $item->name];
    })
     
    

    Then configure your pivotData

    CheckboxList::make('amenities')
        ->label('Amenities')
        ->columnSpanFull()
        ->relationship('amenities', 'name', 'amenities.pivot.amenity_type_id')
        ->options($options)
            ->pivotData(function ($item, $state) {
                return ['amenity_type_id' => $item->amenity_type_id];
             })
         ->columns(3),