Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paginate and sort results in Laravel?

I need to paginate the results and sort them using sortBy(), without losing the pagination links. I also need to use a resource to return the results.

$sorted = Model::paginate(10)->sortBy('name');

$results = \App\Http\Resources\MyResource::collection($sorted);

Doing this breaks the pagination links (I get only the data part).

$paginated = Model::paginate(10);

$results = \App\Http\Resources\MyResource::collection($paginated);

return $results->sortBy('name');

This also doesn't work. Any ideas?

like image 769
Josh Avatar asked Jan 01 '23 14:01

Josh


1 Answers

Using the getCollection() and setCollection() method in the paginator class, You can update the pagination result without losing the meta data.

$result = Post::orderBy('another_key')->paginate();
$sortedResult = $result->getCollection()->sortBy('key_name')->values();
$result->setCollection($sortedResult);

return $result;
like image 157
rufaidulk Avatar answered Jan 04 '23 02:01

rufaidulk