Sorts¶
A sort declares one key your collection endpoint accepts in the sort query
parameter, so clients can order results — GET /tracks?sort=title,-trackNumber.
This page covers marking a field sortable, the one built-in sort, writing a
computed sort, and the handler contract that turns requested sorts into an
ordered query.
Like a filter, a sort in this library is metadata only: a value
object that names the sort key and the column it maps to, carrying no behaviour.
Turning a sort into an ordered query — an ORDER BY, a usort, a search-engine
sort clause — lives in an adapter-provided SortHandlerInterface,
not in the sort itself. This keeps core decoupled from any data layer: there is no
generic query interface, and the split mirrors exactly how filters
and field constraints work.
This page is the declaration side — marking fields sortable and writing sort
value objects. If you followed the getting-started handler and just want
?sort=title working end to end, the smallest executing side is the reference
ArraySortHandler wired up
the way the catalog's
CriteriaApplier does it
(shown under Executing sorts); see Adapters for
pushing the ordering down to a real store.
Marking a field sortable¶
The common case needs no explicit sort declaration. Calling ->sortable() on a
field tells the resource to derive a sort for it automatically. The
TrackResource marks
two fields sortable:
public function fields(): array
{
return [
Id::make(),
\haddowg\JsonApi\Resource\Field\Str::make('title')->required()->sortable(),
\haddowg\JsonApi\Resource\Field\Integer::make('trackNumber')->min(1)->sortable(),
// …
];
}
Clients can now request ?sort=title, ?sort=-trackNumber (a leading - means
descending), or both at once — ?sort=trackNumber,-title — where the order of
the keys is the order of significance: the first is the primary sort, later keys
break ties.
orders primarily by trackNumber ascending, then by title descending within
each trackNumber. (SortsTest
asserts exactly this ordering.)
allSorts(): derived plus explicit¶
AbstractResource::allSorts() is the full set of sorts a resource accepts. It
walks the fields and produces a SortByField for each one marked ->sortable()
(keyed by the field name, targeting the field's column and falling back to the
field name, and carrying the field's describedAs() description), then merges in
whatever sorts() returns. The merge is keyed by sort
key, later entries win, so an explicit sorts() entry overrides a
field-derived one with the same key. A sort family
is the exception: it never answers its bare prefix, so it sits beside an exact sort
with the same key instead of replacing it.
// AbstractResource::allSorts() — derived first, explicit sorts() merged over them
foreach ($this->allFields() as $field) {
if ($field->isSortable()) {
$derived[] = SortByField::make($field->name(), $field->column() ?? $field->name())
->describedAs(...); // the field's description, when it has one
}
}
return SortMatcher::merge($derived, $this->sorts());
You only ever override sorts() for the non-trivial cases below — for the common
field sort, ->sortable() is enough.
SortByField: the one built-in¶
SortByField is a final readonly value
object with a make($key, ?$column) named constructor; the column defaults to the
key. You rarely construct it by hand — ->sortable() derives it for you. Declare
one explicitly in sorts() only when the sort key is not the field name, or
when you want a column override:
use haddowg\JsonApi\Resource\Sort\SortByField;
public function sorts(): array
{
return [
SortByField::make('name', 'last_name'), // expose ?sort=name, order by the last_name column
];
}
Sorting by a related field: ->through()¶
SortByField::through() sorts by a field of the type a path of to-one relations reaches:
use haddowg\JsonApi\Resource\Sort\SortByField;
public function sorts(): array
{
return [
SortByField::make('campaignStart', 'startDate')->through('campaign'), // ?sort=-campaignStart
SortByField::make('advertiserName', 'name')->through('campaign.advertiser'),
];
}
The path names relations by their API names and the column names a field of the reached type,
resolved the way a filter's path is: the
field's storedAs() decides the member a data layer orders by, and a column naming no stored
field of that type fails resolution with a \LogicException. A path crossing a to-many has no
single value to order by and fails resolution too, which adapters raise when they warm up.
A row whose relation holds nothing sorts as a null value of a field of the sorted type does:
by the data layer's own order on an offset page, and as the largest value on a cursor page.
Sorts reaching through relations work in defaultSort(), a relation's withSorts() and
defaultSort(), relatedQuery[<path>][sort] and a sort family's resolver, and on offset and
cursor pages alike: a resolved SortByField is a
KeysetSortInterface whose keysetValue() reads
the reached row's field. Resolve one with
ThroughPathResolver::resolveSort($sort, $resource->allFields()), passing the relation it runs
under as a third argument, a RelationHop of the relation and the type declaring it, when it does.
A leading pivot reaches the pivot row of the relation the sort runs under, which is one row
for each member, so a relation's withSorts() can order its members by a pivot field or by a
field of a relation the pivot row holds:
BelongsToMany::make('playlists', 'playlists')
->fields(DateTime::make('addedAt')->readOnly())
->withSorts(
SortByField::make('added', 'addedAt')->through('pivot'), // ?sort=-added
SortByField::make('adder', 'name')->through('pivot.addedBy'),
);
It applies on the relation's related and relationship endpoints and in
relatedQuery[<relation>][sort]. A pivot anywhere else follows a to-many, so it reaches many
pivot rows and fails resolution for a sort; filter by it instead. See
reaching a pivot row.
defaultSort(): the order with no ?sort¶
allSorts() only governs which sorts a collection accepts. With no sort
parameter a collection is returned in storage order, which also makes
pagination non-deterministic. Override defaultSort() to declare a default order
applied only when the request carries no ?sort — an explicit ?sort=
overrides it entirely (the default is never appended to a requested sort). The
AlbumResource orders
albums newest-first by default:
use haddowg\JsonApi\Resource\Sort\SortByField;
use haddowg\JsonApi\Resource\Sort\SortDirective;
public function defaultSort(): array
{
return [
new SortDirective(SortByField::make('releasedAt'), descending: true),
];
}
GET /albums (no ?sort) now orders by releasedAt descending; GET
/albums?sort=title orders by title ascending and ignores the default.
Each entry is a SortDirective — the same SortInterface +
direction pair a data layer builds for a requested sort, most significant first —
so a default flows through the resource's sort handler on the
same path as a requested sort, with no new execution arm. A default must
therefore name a sort the handler can execute (a SortByField for the reference
ArraySortHandler, or a custom sort with a
handler arm). defaultSort() defaults to [] — no default order. The data layer
falls back to it whenever the request's parsed sort list is empty:
$requested = $request->getSorting();
if ($requested === []) {
$directives = $resource->defaultSort(); // [] ⇒ storage order
// … apply $directives through the same handler a requested sort uses
}
A to-many relation can declare its own default read order with defaultSort() on the
relation builder, which replaces the related type's default for that relation. See
relations.
The SortInterface contract¶
Every sort implements
Resource\Sort\SortInterface, whose sole
member is the key:
The -key direction prefix is not part of the key — it is parsed off the
request and handed to the handler as a separate descending flag. Concrete sorts
add their own public readonly fields (a column, an expression, …) that a handler
reads when it orders the query.
Computed and multi-column sorts¶
For sorts that don't map to a single sortable field — a computed expression, an
ordering across columns — write a custom SortInterface and return it from
sorts(). The ArtistResource
exposes ?sort=trackCount, an ordering by a computed trackCount that has no
single backing column:
TrackCountSort is a
plain value object carrying whatever its handler needs — here, the key and the
property to read:
use haddowg\JsonApi\Resource\Sort\SortInterface;
final readonly class TrackCountSort implements SortInterface
{
public function __construct(
public string $key = 'trackCount',
public string $column = 'trackCount',
) {}
public function key(): string
{
return $this->key;
}
}
For it to do anything, a handler must recognise it — see Executing sorts below. A custom sort and the handler arm that understands it are written together.
Sort families: keys matched by prefix¶
Some sort keys are data rather than vocabulary: a campaign's placeholder values,
custom fields, EAV attributes, members of a JSON column. You can't list them in
sorts() because they differ per record set, but clients still want
?sort=value.cap,-value.end_date.
A SortFamily answers every key that
starts with a prefix and a dot. You give it the prefix and a resolver that turns
the rest of the key, the suffix, into a concrete sort:
use haddowg\JsonApi\Request\JsonApiRequestInterface;
use haddowg\JsonApi\Resource\Sort\SortFamily;
use haddowg\JsonApi\Resource\Sort\SortInterface;
public function sorts(): array
{
return [
SortFamily::make('value', fn(string $suffix, JsonApiRequestInterface $request): ?SortInterface
=> $this->placeholders->exists($suffix)
? new PlaceholderValueSort('value.' . $suffix, $suffix)
: null),
];
}
?sort=-value.end_date calls the resolver with end_date and sorts descending by
the sort it returns. The rules:
- The suffix is everything after
<prefix>., dots included, sovalue.a.bhands the resolvera.b. The bare prefix never matches:?sort=valueis unrecognized unless an exact sort is keyedvalue, and the two can sit side by side. - Returning
nullrejects the key with the usual400SortParamUnrecognized, naming the full key. - The sort you return must be keyed by the full requested key (
value.end_dateabove). Anything else is a\LogicExceptionnaming the family, since a data layer and a cursor token both identify the sort by that key. - An exact key always wins over a family. When two families' prefixes both fit,
the longer prefix decides, and its
nullis final.
By default any non-empty suffix without a comma is accepted. Narrow it with
withSuffixPattern(), a regular-expression fragment the whole suffix must match.
A suffix that fails it is rejected without calling the resolver, and the pattern
also lands in the OpenAPI document.
Stick to syntax PCRE and ECMA-262 share:
A family is never handed to a sort handler. Matching replaces it with the sort its
resolver returns, so the handler arm for PlaceholderValueSort is the same arm a
fixed custom sort would need. Families work wherever a sort key does: the primary
sort, a relation's withSorts(), the
Relationship Queries profile's relatedQuery[<path>][sort], and a
defaultSort() directive whose sort carries a key a family answers.
To write your own family, implement
SortFamilyInterface: key()
returns the prefix, suffixPattern() the fragment and resolve($suffix, $request)
the sort.
Describing a sort¶
SortByField and SortFamily each have a describedAs() wither that returns a copy
carrying a description of the order the key gives. A ->sortable() field's sort already
carries the field's description, and so does the sort a relation derives from a
pivot field; declare the key explicitly in sorts() to say something
different:
public function sorts(): array
{
return [
SortByField::make('name', 'last_name')->describedAs('Alphabetical by surname.'),
SortFamily::make('value', $resolver)->describedAs('By a placeholder value.'),
];
}
The OpenAPI document shows the descriptions the way it shows a described enum's values,
following the projector's EnumDescriptionMode: a markdown table of the keys appended to
the sort parameter's description, and the map
x-sort-descriptions from each
described exact key to its description. A family's description goes in its
x-sort-families entry. A custom sort opts in by implementing
DescribedSort.
The sort example¶
The sort parameter's example is the order worth copying: a relation's
default read order on its related and relationship
endpoints, else the type's defaultSort(), else the first exact sort ascending, such as
["title"]. A type with only families gets no example. Override sortExample() on the
resource to name one of your own:
It applies to the type's collection and to the endpoints of a relation to the type that
declares no order of its own. Adapters report it through the DeclaresSortExample
metadata interface.
Deprecating a sort¶
SortByField and SortFamily each have a deprecated() wither that returns a copy
marked deprecated, keeping any description. A ->sortable() field declared deprecated() derives a deprecated
SortByField on its own.
public function sorts(): array
{
return [
SortByField::make('name', 'last_name')->deprecated(),
SortFamily::make('value', $resolver)->deprecated(),
];
}
It is documentation only: the key still sorts. OpenAPI cannot deprecate a single enum
value, so the document lists the deprecated keys, without the -, under the sort
schema's x-deprecated-sorts, and a
deprecated family's entry in x-sort-families carries deprecated: true. A custom sort or
family opts in by implementing haddowg\JsonApi\Resource\Deprecatable.
Executing sorts¶
The metadata never orders anything on its own. Execution lives in a
SortHandlerInterface, and the whole ordered sort is applied in
one call:
This is the key shape: the handler receives the full ordered list of
directives — most significant first — not one directive at a time. Sorting does
not compose commutatively, and the correct way to combine keys differs per data
layer: SQL appends ORDER BY terms in significance order, while an in-memory
re-sort must compare keys in a single cascading comparator. Handing the handler
the full list lets each adapter compose natively and keeps the request's first
sort field the primary key everywhere, as the spec requires.
Each element is a
SortDirective — a final readonly
pair of the matched sort and its direction:
final readonly class SortDirective
{
public function __construct(
public SortInterface $sort,
public bool $descending,
) {}
}
Reading the requested sorts¶
The requested sorts reach you through the request's parsed sort list. From an
operation handler read it via queryParameters()->sort
(a list<string> with the leading - preserved), or directly from the request
with JsonApiRequestInterface::getSorting(). You match each requested key against
the type's allSorts(), build a SortDirective per match, and hand the whole
list to the handler.
SortMatcher does the matching the way
the rest of the library does, sort families included:
use haddowg\JsonApi\Resource\Sort\SortMatcher;
// 400 SortingUnsupported / SortParamUnrecognized on a bad key
$directives = SortMatcher::directives($request->getSorting(), $resource->allSorts(), $request);
// one key, or null when nothing declared answers it
$sort = SortMatcher::match($resource->allSorts(), 'value.cap', $request);
// a related endpoint's vocabulary: the related type's sorts, then the relation's
$sorts = SortMatcher::merge($relatedResource->allSorts(), $relation->sorts());
The request is optional for exact keys, but a family needs it to resolve one, so
matching a family key without it is a \LogicException. merge() lets a later
sort replace an earlier one with the same key, and keeps a family beside an exact
sort sharing its key.
The catalog's
CriteriaApplier does
exactly this:
$requested = $request->getSorting();
/** @var array<string, SortInterface> $allSorts */
$allSorts = [];
foreach ($resource->allSorts() as $sort) {
$allSorts[$sort->key()] = $sort;
}
$directives = [];
foreach ($requested as $entry) {
$descending = \str_starts_with($entry, '-');
$key = $descending ? \substr($entry, 1) : $entry;
$sort = $allSorts[$key] ?? null;
if ($sort === null) {
continue; // this loop skips an unknown sort key
}
$directives[] = new SortDirective($sort, $descending);
}
$sorted = $this->sorts->apply($directives, $rows);
This loop skips a sort key matching no declared or derived sort and leaves the
order untouched. Whether an unknown key is skipped or rejected is the handler's
call, since core never applies a sort itself. SortMatcher::directives() (above)
rejects it with a 400 SortParamUnrecognized, and so do the Symfony bundle and the
Laravel adapter.
That choice is key-level: an unrecognized key inside the sort family. The
sort family itself is always recognized, so it never trips the
strict query-parameter validation
Server runs by default: an unrecognized query-parameter family (a misspelled
?srot=..., an unregistered custom parameter) is a 400 QueryParamUnrecognized
whatever the handler does with keys.
The reference ArraySortHandler¶
Core ships
Resource\Sort\InMemory\ArraySortHandler
as a reference handler that orders a PHP list<array|object>. It collects the
directives' columns and runs one usort whose comparator cascades through them in
significance order, so the first sort field stays primary:
public function apply(array $sorts, mixed $query): mixed
{
$columns = [];
foreach ($sorts as $directive) {
$sort = $directive->sort;
if (!$sort instanceof SortByField) {
throw new UnsupportedSort($sort);
}
$columns[] = [$sort->column, $directive->descending];
}
// … one usort, comparing each column in turn until one differs
}
It is used by the package's own tests and serves as the canonical adapter
example — it is not a production sort layer. A real adapter pushes the ordering
down to its data store (see Adapters). Note that it understands
only SortByField: a custom sort like TrackCountSort would throw
UnsupportedSort if it reached the handler, so the CriteriaApplier executes the
computed sort in a pre-arm before delegating the field sorts:
// The reference ArraySortHandler only understands SortByField, so a computed
// sort is executed here before the field sorts are delegated.
foreach ($directives as $directive) {
if ($directive->sort instanceof TrackCountSort) {
return $this->sortByTrackCount($rows, $directive->sort, $directive->descending);
}
}
Unsupported sorts¶
If a sort value object reaches a handler that does not recognise it,
Resource\Sort\UnsupportedSort is
thrown. Like UnsupportedFilter, it is a
server configuration error, not a client error, so it renders as a 500 — a
sort was declared (or routed through) with no handler wired to execute it. It is
an AbstractJsonApiException like the rest of the exception
hierarchy, so the error-handler middleware turns
it into a JSON:API error document automatically, and it exposes the offending sort
via its public $sort property.
This is distinct from
SortParamUnrecognized, which is a client 400 for a sort
parameter the server rejects outright; UnsupportedSort is purely about a handler
gap on the server side.
Sorting a cursor page by a custom sort¶
Cursor pagination walks a total order and
writes the boundary row's sort values into each cursor token, so a sort has to
say what its value is for a row. A SortByField reads its column. A custom sort
opts in by implementing
KeysetSortInterface:
final readonly class PlaceholderValueSort implements KeysetSortInterface
{
public function __construct(public string $key, public string $placeholder) {}
public function key(): string
{
return $this->key;
}
public function keysetValue(mixed $row): mixed
{
return $row->placeholderValue($this->placeholder); // scalar, null or a DateTime
}
}
keysetValue() runs only for the rows a token is minted from. The data layer's
arm for the sort still does the ordering and the "strictly after this value"
comparison, with null ordered as the largest value; see
the keyset execution toolkit. A
custom sort that doesn't implement the interface stays a 500 UnsupportedSort
under cursor pagination.
Next / see also¶
- Fields —
->sortable()and the field DSL. - Adapters — the handler side: ordering a real data store.
- Filters — the same metadata/handler split for the
filterparameter. - Pagination — windowing the ordered collection.
- Resource classes —
sorts(),allSorts(), and the derivation rule. - Relations — scoping sorts (and filters) to a related to-many collection with
withSorts()/withFilters().