Sunday, February 20, 2022

[FIXED] Laravel sort by descending or ascending with pagination

Issue

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"

Solution

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



Answered By - Ron van der Heijden

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.