Skip to content

Sorting

plokko edited this page Feb 25, 2021 · 4 revisions

Like with filtering you can declare sorting query parameters via the OrderBy parameter in many ways:

$resource->orderBy->add('<SORTING_PARAMETER>'[,<FIELD>][,<DIRECTION>]);
$resource->orderBy-><SORTING_PARAMETER>;
$resource->orderBy['<SORTING_PARAMETER>'];
$resource->orderBy-><SORTING_PARAMETER>([,<FIELD>][,<DIRECTION>]);

For each filter you can specify a related table field to order with the field('<FIELD>') function and a default sorting direction with defaultOrder('<DIRECTION>'). If you want the sorting direction to be fixed and not modifiable by the user you can use the direction('<DIRECTION>') method.

If you want to customize the sorting you can pass a callback as the field parameter; the query where the sorting will be applied will be passed as first argument and the sorting direction as second argument.

Example:

$resource->orderBy->email->field('email');
$resource->orderBy->name->field('username')->defaultOrder('desc');
// Forced ascending
$resource->orderBy->add('name-asc','username','asc');
// Example custom filter
$resource->orderBy->test1->field(function($query,$direction){
    $query->orderBy('email',$direction)
          ->orderBy('name',$direction)
          ->orderBy('id','asc');        
});

Order query parameter

The filter query parameter can be set with the $orderField parameter of the ResourceQuery. The filter can be specified as a key value with the sorting parameter as key and the direction as a value or by using one of the two short syntax (as string, comma separated):

  • <sorting_parameter>[:<direction>]
  • [+|-]<sorting_parameter> where prepending "+" means ascending order and "-" descending order

Example:

page?order_by[field1]=&order_by[field2]=asc&order_by[field3]=desc

Or

page?order_by=field1,field2:asc,field3:desc

Or

page?order_by=field1,^field2,-field3
Clone this wiki locally