Skip to content

Sorting

Column sorting

To make a column sortable, you may pass the sortable argument to the column's make() method:

php
TextColumn::make('name', sortable: true);

Alternatively, you may use the sortable() and notSortable() methods:

php
TextColumn::make('name')->sortable();
TextColumn::make('name')->notSortable();

Default Table Sorting

You may set the $defaultSort property on your Table class to define the default sorting column:

php
class Users extends Table
{
    protected ?string $defaultSort = 'name';
}

If you want to sort in descending order by default, simply prefix the column name with a minus sign:

php
protected ?string $defaultSort = '-name';

Sort by a mapped value

For columns like statuses, it is common to map the column value to a human-readable string or to a translated string. This can be done using the mapAs method. However, when sorting, you probably want to sort by this mapped value instead of the original value. You can do this by calling the sortUsingMap() method on the column. This requires the mapAs method to be called first with an array:

php
TextColumn::make('status', sortable: true)->mapAs([
    'is_active' => 'Actief',
    'is_deleted' => 'Verwijderd',
    'is_pending' => 'In afwachting',
])->sortUsingMap();

If you want to sort by another mapping, you can pass the mapping array to the sortUsingMap() method:

php
TextColumn::make('status', sortable: true)->sortUsingMap([
    'is_active' => 1,
    'is_deleted' => 3,
    'is_pending' => 2,
]);

Under the hood, this calls the sortUsingPriority() method, which sorts the column based on the priority of the given values. The example above will sort the column in the order of is_active, is_pending, and is_deleted. To achieve this with the sortUsingPriority() method, you would do the following:

php
TextColumn::make('status', sortable: true)->sortUsingPriority([
    'is_active', 'is_pending', 'is_deleted',
]);

Sort by Relationships

If you want to sort by a column on a related Model, you must install the Eloquent Power Joins package by Kirschbaum:

bash
composer require kirschbaum-development/eloquent-power-joins

Customizing the Query

You can customize how the sorting is applied to the query by passing a closure to the sortUsing() method. It takes two arguments: the Eloquent Query Builder and the SortDirection enum:

php
use Illuminate\Database\Eloquent\Builder;
use InertiaUI\Table\SortDirection;

TextColumn::make('name')->sortUsing(function (Builder $query, SortDirection $direction) {
    $query->orderBy('name', $direction->value);
});

Alternatively, you may use the sortUsing argument on the column's make() method. Besides a Closure, you may also pass an invocable class:

php
TextColumn::make('name', sortUsing: new CustomSortByName);