Tricks

Customize table search

May 31, 2022
Z3d0X
Table builder

If you need to customize the table search, you can override applySearchToTableQuery on a Livewire component that uses \Filament\Tables\Concerns\InteractsWithTable trait.

This is useful if you need to search by a column that is not in the table or if you are going to use Filament in an existing project that already has a complex search scope already setup.

Note: if you are using Filament Admin Panel this would be your "ListRecords" Page

Example

//App\Filament\Resources\PostResource\ListPosts
 
public function isTableSearchable(): bool
{
return true;
}
 
protected function applySearchToTableQuery(Builder $query): Builder
{
if (filled($searchQuery = $this->getTableSearchQuery())) {
//In this example a filter scope on the model is used
//But you can also customize the query right here!
return $query->filter(['search' => $searchQuery]);
}
 
return $query;
}
//App\Models\Post
 
public function scopeFilter($query, array $filters)
{
$query->when($filters['search'] ?? null, function ($query, $search) {
$query->where('title', 'like', '%'.$search.'%')
->orWhere('author_name', 'like', '%'.$search.'%');
})
->when($filters['status'] ?? null, function ($query, $status) {
$query->where('status', '=', $status);
});
}
avatar

applySearchToTableQuery is not exist in ListRecords

avatar

Just what I needed! Thnx!