Filament Select with Relationship: Custom Label for titleAttribute Options

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.

avatar

Ok - now how does one show a table with a sortable colum with this ?

avatar

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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 60 courses (1084 lessons, total 42 h 44 min)
  • 80 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials