F
Filament8mo ago
Neamix

Add relation in select menu

Hey folks, i have 2 models coupons and users and each coupons belongsTo one user and each user have firstname and surname so i want to create a select menu contain users firstname and surname i tried to use this
Select::make('user_id')
->relationship(name: 'user', titleAttribute: function ($record) {
dd($record);
})
->searchable()
->optionsLimit(20)
Select::make('user_id')
->relationship(name: 'user', titleAttribute: function ($record) {
dd($record);
})
->searchable()
->optionsLimit(20)
but it keep return null in create and return coupon record not user in edit
Solution:
@Neamix you should use getOptionLabelFromRecordUsing() Here's the example from one of our tutorials: ```...
Jump to solution
4 Replies
403gtfo
403gtfo8mo ago
I hope this helps, an example I how I did something similar (if I understand what you are doing right. I am sure there is a much better way.
// At the top of the function
$staff = Staff::all();


// in the for fields
Select::make('staff_id')
->label('Staff member')
->relationship('staff', 'staff_id')
->preload()
->searchable(['first_name', 'last_name'])
->options(
$staff->mapWithKeys(
function ($staff) {
$staffArray = [];
$staffArray[$staff->id] = $staff->first_name ." ". $staff->last_name;
return $staffArray;
}
)
)->required(),
// At the top of the function
$staff = Staff::all();


// in the for fields
Select::make('staff_id')
->label('Staff member')
->relationship('staff', 'staff_id')
->preload()
->searchable(['first_name', 'last_name'])
->options(
$staff->mapWithKeys(
function ($staff) {
$staffArray = [];
$staffArray[$staff->id] = $staff->first_name ." ". $staff->last_name;
return $staffArray;
}
)
)->required(),
Solution
Povilas K
Povilas K8mo ago
@Neamix you should use getOptionLabelFromRecordUsing() Here's the example from one of our tutorials:
Forms\Components\Select::make('car_id')
->relationship(
name: 'car'
)
->getOptionLabelFromRecordUsing(fn (Model $record) => "{$record->name} ({$record->year})")
Forms\Components\Select::make('car_id')
->relationship(
name: 'car'
)
->getOptionLabelFromRecordUsing(fn (Model $record) => "{$record->name} ({$record->year})")
Povilas K
Povilas K8mo ago
And yeah, don't forget ->searchable(['first_name', 'last_name'])
403gtfo
403gtfo8mo ago
That is so much cleaner than my way XD
Want results from more Discord servers?
Add your server