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('company.name');

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')) {

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

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

Related Posts