Filters usually used in filament tables in the table method $table->filters()
1// ...2public function table(Table $table): Table3{4 return $table5 ->filters([ 6 ....7 ]),8}
Your First Filter
Let's say we have a table contains posts, and each post has category, so, let's create a custom filter, to filter posts by category.
Pre-requist
First we need to have a PostResource
, and Category
model relationship.
1...2class Post extends Model3{4 public function category(): BelongsTo5 {6 return $this->belongsTo(Category::class);7 }8}
Create The Filter
In your app/Filament/PostResource
folder. Create a new folder called Filters
, and you can create the class CategoryFilter
.
Let's first create the class, then we'll explain what's inside, shall we
1<?php 2 3namespace App\Filament\Resources\PostResource\Filters; 4 5use Filament\Tables\Filters\SelectFilter; 6 7class CategoryFilter extends SelectFilter 8{ 9 public static function getDefaultName(): ?string10 {11 return 'category';12 }13 14 protected function setUp(): void15 {16 parent::setUp();17 18 $this->label('Filter By Category');19 20 $this->placeholder('Select a category to filter');21 22 $this->relationship('category', 'name');23 24 $this->searchable();25 }26}
Let's explain the above filter
- We extends
SelectFilter
filament class, to filter by dropdown -
getDefaultName
, is the name of your custom filter, to use it when you need it. - we extends the parent
setUp
of theSelectFilter
class to make our own modifications - the
label
is self explanatory, to set a label for the filter - the
placeholder
, is also self explanatory - the
relationship
, is the method to the categories relationship - the
searchable
method, is to make the dropdown searchable.
PS: You can use pretty much every method came with the Select component.
Apply it
If you want to apply this filter in PostResource
. Do the following
1public function table(Table $table): Table2{3 return $table4 ->filters([5 CategoryFilter::make(), 6 ]),7}
Other Filters To Choose From
Filament came by default with multiple classes to support filtering system, which is
- Filter: the default filter class to choose
- SelectFilter: to select between multiple options
- TernaryFilter: to set a boolean filteration
Conclusion
Custom Filters in filament are very handy if you are the type of developer who like to take control, and use something in multiple places, and with custom filters you can use even form
method to make your filter more advanced, and serve your needs.
This is all what I have today, hope you learn something from it, and see yea in another article.
Peace ✌️