F
Filament14mo ago
Malja

Searchable select using model's attribute as label

Hi all, I have a model Pet, that belongs to User:
class Pet extends Model {
// ...
public function owner(): BelongsTo {
// This sets the field name in Pet, right? ↓
return $this->belongsTo(User::class, 'owner_id');
}
// ...
}
class Pet extends Model {
// ...
public function owner(): BelongsTo {
// This sets the field name in Pet, right? ↓
return $this->belongsTo(User::class, 'owner_id');
}
// ...
}
class User extends Model {
// ...
public function pets(): HasMany {
// This sets the field name in Pet, right? ↓
return $this->hasMany(Pet::class, 'owner_id');
}
// ...
public function fullName(): Attribute {
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}"
);
}
// ...
}
class User extends Model {
// ...
public function pets(): HasMany {
// This sets the field name in Pet, right? ↓
return $this->hasMany(Pet::class, 'owner_id');
}
// ...
public function fullName(): Attribute {
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}"
);
}
// ...
}
However, I have a problem creating a new Pet for a specific User:
// from PetResource.php
public static function form(Form $form): Form {
return $form->schema([
Forms\Components\Select::make('owner_id')
->label('Owner')
->getSearchResultsUsing(fn ($search): array =>
User::query()
->where('first_name', 'ilike', "%{$search}%")
->orWhere('last_name', 'ilike', "%{$search}%")
->get()
->toArray()
)
->searchable()
->getOptionLabelUsing(fn ($value): string => User::query()->find($value->id)?->fullName)
->required()
]);
}
// from PetResource.php
public static function form(Form $form): Form {
return $form->schema([
Forms\Components\Select::make('owner_id')
->label('Owner')
->getSearchResultsUsing(fn ($search): array =>
User::query()
->where('first_name', 'ilike', "%{$search}%")
->orWhere('last_name', 'ilike', "%{$search}%")
->get()
->toArray()
)
->searchable()
->getOptionLabelUsing(fn ($value): string => User::query()->find($value->id)?->fullName)
->required()
]);
}
The problem is, that no matter what I do in getSearchResultsUsing and getOptionLabelUsing, I won't get User's fullName to be shown. I tried: - Using pluck('last_name', 'id') instead of get. This shows the last_name, but getOptionLabelUsing is not called. - Using relationship('owner', 'last_name'). This does not allow using fullName instead of lastName.
Do you have any suggestions? Thank you.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server