1

I would like to perform a sort by ascending or descending together with pagination

  return \App\User:: paginate($request->per_page);

how do i add the sort by so something like this

return \App\User:: paginate($request->per_page)-sortBy(
    $request->sort_field, $request->sort_order
  );

bur the above fails where

$request->sort_order //asc or desc

the above returns an error of

"asort() expects parameter 2 to be integer, string given"
Geoff
  • 4,505
  • 14
  • 65
  • 156

3 Answers3

1

I can't see the syntax in where you may enter the order (DESC or ASC) in the Laravel docs, Try this :

if ($request->sort_order == 'asc') {
   return \App\User::paginate($request->per_page)->sortBy($request->sort_field); 
}
return \App\User::paginate($request->per_page)->sortByDesc($request->sort_field); 

Read more in the docs : https://laravel.com/docs/5.5/collections#method-sortby

teeyo
  • 3,155
  • 3
  • 20
  • 35
1

You could try something like

User::orderBy($request->sort_field, $request->sort_order)->paginate($request->per_page);

Source: https://laracasts.com/discuss/channels/laravel/combining-paginate-with-orderby

Ron van der Heijden
  • 13,198
  • 7
  • 52
  • 79
0

Using Eloquent you can sort and paginate your data quickly and easily.

For example, I want to sort all users that exist in the user table.

//---Sort Ascending
$users = User::orderBy('id', 'ASC')->Paginate(10);
//---Sort Descending
$users = User::orderBy('id', 'DESC')->Paginate(10);