Single-column API sorting, with direction control
// Handles /dogs?sort=name and /dogs?sort=-nameRoute::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,-weightRoute::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);});