Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Sorting Your API Results

Single-column API sorting, with direction control

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

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

// Handles ?sort=name,-weight
Route::get('dogs', function (Request $request) {
// Grab the query parameter and turn it into an array exploded by ,
$sorts = explode(',', $request->input('sort', ''));
 
// Create a query
$query = Dog::query();
 
// Add the sorts one by one
foreach ($sorts as $sortColumn) {
$sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc';
$sortColumn = ltrim($sortColumn, '-');
 
$query->orderBy($sortColumn, $sortDirection);
}
 
// Return
return $query->paginate(20);
});

Like our articles?

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

Recent New Courses