F
Filament11mo ago
Wirkhof

Custom query for table column text

I am storing an array of IDs in a table column car_liked which is a multiple select input field , e.g. ["34","134","159"]. And in the table view I want to show not the IDs stored, but the names of those cars. So, I need to make a query to get records 34, 134, 159 and pluck the name of each of those rows and echo it in the table list view column car_liked. How to do that? Currently, I am doing this, but it outputs just the IDs separated by the coma. like 34, 134, 159 But I would like to have Ford Bronco, VW Golf, Audi Q5 instead. My code is:
Tables\Columns\TextColumn::make('car_liked')
->label(__('Car Liked'))
->sortable()
->searchable(),
Tables\Columns\TextColumn::make('car_liked')
->label(__('Car Liked'))
->sortable()
->searchable(),
7 Replies
Wirkhof
WirkhofOP11mo ago
The table where the ids are from is cars. In the form I am getting the values like:
Select::make('car_liked')
->label('Car Liked')
->multiple()
->options(Car::all()->pluck('name', 'id'))
->searchable(),
Select::make('car_liked')
->label('Car Liked')
->multiple()
->options(Car::all()->pluck('name', 'id'))
->searchable(),
Wirkhof
WirkhofOP11mo ago
But that is for Form, right? I want to display it in Table as a standard record listing and one of the columns will have the liked cars
Wirkhof
WirkhofOP11mo ago
The Form part is not an issue Thanks, how would you do it with ->formatStateUsing(fn (string $state): string => __("statuses.{$state}")) ? in my case
Tieme
Tieme11mo ago
Assuming the state is array you can do something like this
->formatStateUsing(function ($state){
$Cars = Car::whereIn('id', $state)->pluck('name');
$Names = [];
foreach($Cars as $Car)
{
$Names[] = $Car->name;
}

return implode($Names,', ');
})
->formatStateUsing(function ($state){
$Cars = Car::whereIn('id', $state)->pluck('name');
$Names = [];
foreach($Cars as $Car)
{
$Names[] = $Car->name;
}

return implode($Names,', ');
})
Wirkhof
WirkhofOP11mo ago
Thank you. I am getting Expected type 'null|array'. Found 'string'. for ', ' in implode part for some reason. Also, when I try to do just return $Names; it gives me this error
count(): Argument #1 ($value) must be of type Countable|array, string given
count(): Argument #1 ($value) must be of type Countable|array, string given
Perhaps it has something to do with the fact that not all items in my table have car_liked? Some are empty. Can there be some check for empty records? Well, it seems that $state is a string and not an array for some reason. I guess I have to convert it to an array first? OK, the problem was with the ->name part. It already is plucked so no need for that.
Want results from more Discord servers?
Add your server