Tricks

Filter by multiple Spatie Tags

Nov 25, 2022
Mads Møller
Table builder, Admin panel

If you want to filter your records by Spatie Tags, then you can use the below snippet. It allows you to filter by one or multiple tags at the same time. In this example I use the type my-tag and add the following code to the Resource table section:

public static function table(Table $table): Table
{
return $table
->columns([
// ...
])
->filters([
SelectFilter::make('tags')
->multiple()
->options(Tag::getWithType('my-tag')->pluck('name', 'name'))
->query(function (Builder $query, array $data): Builder {
return $query->when($data['values'], function (Builder $query, $data): Builder {
return $query->withAnyTags(array_values($data), 'my-tag');
});
})
]);
}
avatar

Awesome trick. You can make them searchable also, but doesn't work with multiple tags.

Tables\Columns\SpatieTagsColumn::make('tags')->type('notes')
->searchable(query: function (Builder $query, string $search): Builder {
return $query->when($search, function (Builder $query, $search): Builder {
$tags = Tag::where('name', 'iLIKE', '%'.$search.'%')
->pluck('name', 'name')->toArray();
 
return $query->withAnyTags(array_values($tags), 'notes');
});
}, isIndividual: true)
->toggleable(),