Similar to pagination, sorting is another complementary technical for loading large data set.

In this tutorial, we are going to implement sorting for our articles table.

Table Of Content

  1. Understanding GraphQL sorting mechanism
  2. Implementing sorting
  3. The end
1. Understanding GraphQL sorting mechanism

The mechanism behind sorting is much simpler comparing to pagination. We pass in a field and its order to the request and we get the results accordingly.

In most cases, sorting goes together with pagination and we are going to do the same for our example.

2. Implementing sorting

An imaginary sorting and pagination request would look like this:

The only additional code block is the sort parameter:

GraphQL Extensions provides reusable classes for sorting similar to pagination.

First step is to add available sort parameters to the ArticlesConnection field. To keep our tutorial simple, we will make "id" field available as the only sort parameter.

Modify build method of ArticlesConnection class:

We are using the SortingParamsType class from GraphQL Extensions to build the sorting parameter.

Next step is to make resolve method capable of sorting the results based on our request. Normally this method will delegate to the other service class from business layer, and the service class will sort the results with some sort of database calls. However, because our fake repository class simply returns a static array, we are going to sort with PHP array method uasort.

Modify resolve method of ArticlesConnection class:

Note the value of "DESC" is -1 and "ASC" is 1 from $args.

That is all the change we need for ArcilesConnection class and the final file should be as shown below:

Lastly, we need to create a simple request to sort the result using id field:

Create a new file tutorial-sorting.php:

Access the page from the browser of your choice via the URL http://your-local-php-server/tutorial-sorting.php.

You should expect a JSON output as shown below if you have followed this tutorial correctly:

Try to change the order parameter's value(DESC or ASC) and see how GraphQL sorting reflects.

4. The End

Next tutorial, we will implement search feature.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.