This post shows how to quickly add sort functionality to your eloquent models, providing your consumers a
simple easy to understand interface for sorting results.
It should allow ascending and descending sorting over multiple fields, the following demonstrates the
simple functionality that can be achieved.
In this example a list of apps sorted by descending name and ascending created datetime should be returned to the
consumer of the API.
If you don’t specific the parameter for the sort function the input will be taken from the query
string, by default this takes the value from the sort parameter. Adding the parameter in the
function call overwrites this value.
Adding the SortableTrait (see below) to the eloquent model provides the sorting functionality, which
provides the functions seen above.
So, to get started, you should define which model attributes you want to make sortable. You may do this using
the $sortable property on the model. For example, let’s make the name attribute of our Apps model sortable:
If you are using sort request parameter for other purpose, you can change the name of the parameter that
will be interpreted as sorting criteria by setting a $sortParameterName property in your model.
And here is the source code for the sortable trait…