F
Filament3mo ago
Tjiel

Looking for a way to search table based on custom state

Hello all I have the following Textcolumn:
TextColumn::make('object')
->label('Object')
->translateLabel()
->searchable()
->formatStateUsing(fn ($state): string => $state->name ?? $state->mainObject->name)
TextColumn::make('object')
->label('Object')
->translateLabel()
->searchable()
->formatStateUsing(fn ($state): string => $state->name ?? $state->mainObject->name)
The problem is that currently, when searching, an error occurs. This is because you can obviously not saerch a direct relation. But my question is if there is a work around to make it so you can search for both columns at the same time, in this case the object->name column and the object->mainObject->name column.
4 Replies
toeknee
toeknee3mo ago
Adjust the search:
->searchable(query: function (Builder $query, string $search): Builder {
return $query
->where('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%");
})
->searchable(query: function (Builder $query, string $search): Builder {
return $query
->where('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%");
})
as per: https://filamentphp.com/docs/3.x/tables/columns/getting-started you'll just need to join over the object.
Tjiel
Tjiel3mo ago
Ty for the response, based on your suggestion I have tried the following:
TextColumn::make('object')
->label('Rentable product')
->translateLabel()
->searchable(query: function (Builder $query, string $search): Builder {
return $query
->join('objects', 'resourceModels.object_id', '=', 'objects.id')
->where('objects.name', 'like', "%{$search}%");
});
})
TextColumn::make('object')
->label('Rentable product')
->translateLabel()
->searchable(query: function (Builder $query, string $search): Builder {
return $query
->join('objects', 'resourceModels.object_id', '=', 'objects.id')
->where('objects.name', 'like', "%{$search}%");
});
})
But whenever I try to search I get an unknown column 'objects.name' error. ResourceModels is a placeholder for the table name of the resource this column is for.
toeknee
toeknee2mo ago
Did you resolve it?
Tjiel
Tjiel2mo ago
Yeah I found a different way, I forgot to post it here, anyway better late then never:
->searchable(query: function (Builder $query, string $search): Builder {
$objectIds = Object::where('name', 'like', "%{$search}%")->pluck('id');
return $query
->whereHas('mainObject', function (Builder $query) use ($search, $objectIds) {
->whereIn('object_id', $productIds);
});
})
->searchable(query: function (Builder $query, string $search): Builder {
$objectIds = Object::where('name', 'like', "%{$search}%")->pluck('id');
return $query
->whereHas('mainObject', function (Builder $query) use ($search, $objectIds) {
->whereIn('object_id', $productIds);
});
})
Want results from more Discord servers?
Add your server