Laravel

Laravel sorting paginated content

Max Hutschenreiter -

Have you ever been in a situation where you want to run the sortBy method, to sort content by specific relation on an object, but the content is paginated also?

In that scenario, you can only sort per page and not the overall result.

So we have:

$exampleContent->get()->sortBy(***specific-relation***);

and that would work perfectly, but the problem is simple, you canโ€™t call ->paginate(x) on the collection which get() returns.

In that scenario, itโ€™s time to go to the very top of your controller and to append the following uses:
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
Next thing to do, is to implement the following function which enables you to paginate collection, and it needs to look like:
private function paginate($items, $perPage = 5, $page = null, $options = [])
{
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
And than, in that controller, you can use $this->paginate($exampleContent->get(), 10),  which will paginate your collection same way as ->paginate(10) would do on a query, and contain all same functions.

Iโ€™m totally sure that you can find a better place for this function, but Iโ€™ve used the controller just as a quick example for educational purposes.

Tags: Laravel · Laravel sortby · sort pagination · sort paginated content

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • Happy birthday ๐ŸŽ๐ŸŽˆ๐ŸŽ‚ Filip - #

  • Another day another #mandarinacakeshop ๐ŸŽ‚ ๐Ÿ˜€ - #

  • Happy Birthday Ognjen! And marry Christmas to all other ๐ŸŽ„#notacakeshop - #

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan ๐Ÿฅ‚ - #

  • #happybirthday Lidija ๐Ÿพ - #

  • Say hi ๐Ÿ‘‹ to our newest team member โ˜•๏ธ - #

  • #bithday #cake ๐Ÿ˜ป - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday ๐ŸŽ‚ Miloลก - #

  • Happy Birthday ๐ŸŽ‚Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday ๐ŸŽ‚ Ognjen - #

  • Wish you all a merry Christmas ๐ŸŽ„๐ŸŽ - #

See more!

© 2026 42coders All rights reserved.