Filament: Table Filter: CheckboxList with Count of Rows

Free Snippet

If you use Filters with CheckboxList above the table, would you want to show the amount of records per each type?

filamentexamples-thumbnail

How it works

In this example, we're trying to mimic the Booking.com filter with Property Types:

This example is based on the DB Model structure of PropertyType -> HasMany -> Property.

In the Filament Resource code, the main thing is about CheckboxList and its options() method, where we construct the key-value pairs.

app/Filament/Resources/PropertyResource.php:

public static function table(Table $table): Table
{
return $table
->columns([
// ...
])
->filters([
Tables\Filters\Filter::make('type')
->columnSpanFull()
->form([
Forms\Components\CheckboxList::make('type')
->columns(5)
->options(function (): array {
return PropertyType::withCount('properties')
->get()
->mapWithKeys(function (PropertyType $type) {
return [
$type->id => new HtmlString($type->name . " <span class='text-gray-500'>({$type->properties_count})</span>")
];
})
->all();
}),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when($data['type'], fn (Builder $query) => $query->whereIn('property_type_id', $data['type']));
}),
], Tables\Enums\FiltersLayout::AboveContent)

It uses the withCount() feature of Eloquent, read more here.

It also uses Laravel Collection function mapWithKeys(), you can read more about it in the official Laravel docs or in my video course about Collection Examples.

A few of our Premium Examples: