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 one10 foreach ($sorts as $sortColumn) {11 $sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc';12 $sortColumn = ltrim($sortColumn, '-');13 14 $query->orderBy($sortColumn, $sortDirection);15 }16 17 // Return18 return $query->paginate(20);19});