json-api-server/docs/sorting.md

1.0 KiB

Sorting

You can define an attribute as sortable to allow the resource listing to be sorted by the attribute's value.

$type->attribute('firstName')
    ->sortable();
    
$type->attribute('lastName')
    ->sortable();
    
// GET /users?sort=lastName,firstName

You can set a default sort string to be used when the consumer has not supplied one using the defaultSort method on the schema builder:

$type->defaultSort('-updatedAt,-createdAt');

Custom Sorts

To define sort fields with custom logic, or ones that do not correspond to an attribute, use the sort method:

$type->sort('relevance', function ($query, string $direction, Context $context) {
    $query->orderBy('relevance', $direction);
});

Just like fields, sorts can be made conditionally visible or hidden:

$type->sort('relevance', $callback)
    ->visible(function (Context $context) {
        return $context->getRequest()->getAttribute('isAdmin');
    });