Filament Table - Default Sort by Multiple Columns

2025-01-09

When using Filament tables, you can change default sorting not only for one column, but also sort by multiple conditions, with a callback function.

use Filament\Tables\Table;
 
public function table(Table $table): Table
{
return $table
->columns([
// ...
])
->defaultSort('floor');
}

This will sort columns by a floor database column. But the room numbers wouldn't be in order if rooms weren't entered in order.

In this case, the table also should be sorted by room number. So, how to do that?

Well, it's very easy. The defaultSort() method accepts a closure where you can provide orderBy() methods to the Eloquent query.

use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
 
public function table(Table $table): Table
{
return $table
->columns([
// ...
])
->defaultSort(function (Builder $query): Builder {
return $query
->orderBy('floor')
->orderBy('room_number');
});
}

Now, the table is sorted by two database columns. We can see room numbers are in order.

A few of our Premium Examples: