Opening hours: 8am to 6pm
Skopje, Macedonia

Pagination on Collections in Laravel

Pagination on Collections in Laravel

In case, when your data is collection in laravel, the ->paginate() method will not work.

This is a common case when you may want to sort your data on some relation value. ex

$items = $items->get()->sortBy('');

In this case the ->paginate() can’t be used.

What you can do is to inform Laravel that you have the function for this.

Open AppServiceProvider and add this code in the boot method

use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
public function boot()
        if (!Collection::hasMacro('paginate')) {

                function ($perPage = 15, $page = null, $options = []) {
                $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
                return (new LengthAwarePaginator(
                    $this->forPage($page, $perPage), $this->count(), $perPage, $page, $options))

After this you can use ->paginate() even on collections

Related Posts
Leave a Reply

Your email address will not be published.Required fields are marked *