Max Hutschenreiter -
23 Mar 2020
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:
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:
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.