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?


How it works

In this example, we're trying to mimic the 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.


public static function table(Table $table): Table
return $table
// ...
->options(function (): array {
return PropertyType::withCount('properties')
->mapWithKeys(function (PropertyType $type) {
return [
$type->id => new HtmlString($type->name . " <span class='text-gray-500'>({$type->properties_count})</span>")
->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: