How to get only one value in the filament table for with hasMany relationship?
I have two DB tables:
products
id | sku |
---|---|
1 | SKU_1 |
2 | SKU_2 |
product_descriptions
id | product_id | translation_id | name |
---|---|---|---|
1 | 1 | 1 | Opel |
2 | 1 | 2 | Vauxhall |
In my Product model I have hasMany
relationship
public function productDescriptions(): HasMany
{
return $this->hasMany(ProductDescription::class);
}
When I do Tables\Columns\TextColumn::make('productDescriptions.name')
it return all values separated by comma. In my example "Opel, Vauxhall"
Is there any way to manipulate/mutate return value using callback? Let say, return only first value "Opel"?
You can use calculated states.
Tables\Columns\TextColumn::make('productDescriptions.name')
->getStateUsing( function (Model $record){
return $record->productDescriptions()->first()?->name;
});