// Handles /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');returnDog::orderBy($sortColumn)->paginate(20);});
示例13-11我们添加了反转的能力
Example 13-11. 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 starts_with() helper function $sortDirection =starts_with($sortColumn,'-')?'desc':'asc'; $sortColumn =ltrim($sortColumn,'-');returnDog::orderBy($sortColumn, $sortDirection)->paginate(20);});
最后我们对多个字段排序,(例如,?sort=name,-weight)如示例13-12
Example 13-12. JSON API–style sorting
// 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 oneforeach ($sorts as $sortColumn) { $sortDirection =starts_with($sortColumn,'-')?'desc':'asc'; $sortColumn =ltrim($sortColumn,'-'); $query->orderBy($sortColumn, $sortDirection); }// Returnreturn $query->paginate(20);});