Skip to content

Sorting ​

allowedSorts() lists the sorts a request may use. The sort parameter takes a list of names; a - in front sorts descending:

php
QueryBuilder::for(User::class)
    ->allowedSorts('name', 'created_at')
    ->get();
GET /users?sort=-created_at,name

A sort not in the list throws InvalidSortQuery. Sorts are applied in the order of the request.

Another column name ​

php
use MyProgs\QueryBuilder\AllowedSort;

AllowedSort::field('created', 'created_at')

The client sorts by created, the query by created_at.

Default sort ​

php
QueryBuilder::for(User::class)
    ->allowedSorts('name', 'created_at')
    ->defaultSort('-created_at')
    ->get();

The default applies when the request has no sort. defaultSort() and defaultSorts() take several names, and AllowedSort objects:

php
use MyProgs\QueryBuilder\Enums\SortDirection;

->defaultSort(AllowedSort::field('created', 'created_at')->defaultDirection(SortDirection::Descending))

Callback sorts ​

php
AllowedSort::callback('posts', function (Builder $query, bool $descending, string $property) {
    $query->withCount('posts')->orderBy('posts_count', $descending ? 'desc' : 'asc');
})

Custom sort classes ​

Implement MyProgs\QueryBuilder\Sorts\Sort and register it with custom():

php
use Illuminate\Database\Eloquent\Builder;
use MyProgs\QueryBuilder\Sorts\Sort;

class StringLengthSort implements Sort
{
    public function __invoke(Builder $query, bool $descending, string $property): void
    {
        $query->orderByRaw("LENGTH(`{$property}`) ".($descending ? 'DESC' : 'ASC'));
    }
}
php
AllowedSort::custom('name-length', new StringLengthSort, 'name')

The third argument is the property passed to the class, name here.