Sorting Your API Results

Single-column API sorting, with direction control

1// Handles /dogs?sort=name and /dogs?sort=-name
2Route::get('dogs', function (Request $request) {
3 // Get the sort query parameter (or fall back to default sort "name")
4 $sortColumn = $request->input('sort', 'name');
5 
6 // Set the sort direction based on whether the key starts with -
7 // using Laravel's Str::startsWith() helper function
8 $sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc';
9 $sortColumn = ltrim($sortColumn, '-');
10 
11 return Dog::orderBy($sortColumn, $sortDirection)
12 ->paginate(20);
13});

we do the same for multiple columns (e.g., ?sort=name,-weight)

1// Handles ?sort=name,-weight
2Route::get('dogs', function (Request $request) {
3 // Grab the query parameter and turn it into an array exploded by ,
4 $sorts = explode(',', $request->input('sort', ''));
5 
6 // Create a query
7 $query = Dog::query();
8 
9 // Add the sorts one by one
10 foreach ($sorts as $sortColumn) {
11 $sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc';
12 $sortColumn = ltrim($sortColumn, '-');
13 
14 $query->orderBy($sortColumn, $sortDirection);
15 }
16 
17 // Return
18 return $query->paginate(20);
19});

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord