In Filament, when using Select with relationships, you may want to customize the Label of the dropdown options.
Traditionally, this Select label is defined by the titleAttribute
parameter:
Forms\Components\Select::make('car_id') ->relationship( name: 'car', titleAttribute: 'name' ),
But what if you want to show the car year in addition to the name, like this?
The solution is to provide your custom logic as a callback function, in a method called getOptionLabelFromRecordUsing()
.
use Illuminate\Database\Eloquent\Model; // ... Forms\Components\Select::make('car_id') ->relationship( name: 'car', titleAttribute: 'name' ) ->getOptionLabelFromRecordUsing(fn (Model $record) => "{$record->name} ({$record->year})")
As you can see, then you may skip the parameter titleAttribute
, as it's not being used anyway.
The solution is for generally any custom label you want to show in the options.
Notice: you may think that you can use Eloquent Accessors here, but, in my experience, they don't work and will show the error "column not found".
If you want more Filament examples, you can find more real-life projects on our FilamentExamples.com.
Ok - now how does one show a table with a sortable colum with this ?
Can you explain what you want to achieve here? This lesson is focused on a dropdown, so we are unsure on what you mean by sortable table column
it means you can modify how something appears in the table where the relationship name is shown. For example i had a select form that gives the users the option to check out system users based on their user role and i didn't want to show the actual relationship names as stored in the database because it wasn't very user friendly so i used ->getOptionLabelFromRecordUsing() to mask the relationship role names to a more user friendly name