Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Armata's avatar

How to paginate Laravel collection?

Hello.

My question is how to paginate collection in Laravel 5.4?

If I try to use paginate method on collection I get error - Method paginate does not exist.

Thanks.

0 likes
27 replies
bastman69's avatar
#Controller
$items = DB::table('items')->paginate(15);
return view('index')->with('items', $items);
#View
#loop items
{{ $items->links() }}
2 likes
Snapey's avatar

Just use ->paginate(10) instead of ->get() and not just chained on the end of the working query.

If this does not help you will need to post some code.

2 likes
Armata's avatar

Guys, method paginate() doesnt work with collections.

$date = new Carbon;
$date->subDays(16);

$items1 = Item::where('created_at', '<', $date->toDateTimeString())->get();

$items2 = Item::where('created_at', '>', $date->toDateTimeString())->orderBy('created_at', 'desc')->get();

$items = $items2->merge($items1); // I need paginate this

return view('welcome')->with('items', $items);
3 likes
agCepeda's avatar

You can not paginate the collection but you can subdivide it with the method chunk of collection.

$chunks = $books->chunk(2);
$chunks->toArray();

result

[
   [
      ['title' => 'Lean Startup', 'price' => 10],
      ['title' => 'The One Thing', 'price' => 15]
   ],
   [
      ['title' => 'Laravel: Code Bright', 'price' => 20],
      ['title' => 'The 4-Hour Work Week', 'price' => 5],
   ]
]
1 like
Snapey's avatar

The gist proposed by @jlrdw at the start of the answers is pagination for collections?

2 likes
Armata's avatar

Yeah. This gist is working.

// ...
$items = $items2->merge($items1);
$items = $this->paginate($items);
// ...
public function paginate($items, $perPage = 15, $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);
}
8 likes
hakob93's avatar

You can add this method as Collection method in AppServiceProvider. just add this in boot method.

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('');
        });
}

then you can use it as usual - $items->paginate(10);

22 likes
junaidqadir's avatar

@ARMATA - Works fins. One problem though, it shows pages from the root of the site while my on a subpage.

For example I have /search page but pagination links are generated as /?page=1

1 like
junaidqadir's avatar

@ARMATA - Ok I fixed it with passing a parameter.


    public function paginate($items, $perPage = 15, $page = null, 
$baseUrl = null, 
     $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

        $items = $items instanceof Collection ? 
                       $items : Collection::make($items);

        $lap = new LengthAwarePaginator($items->forPage($page, $perPage), 
                           $items->count(),
                           $perPage, $page, $options);

        if ($baseUrl) {
            $lap->setPath($baseUrl);
        }

        return $lap;
    }

1 like
amirgee007's avatar

exactly the same issue is mine now. did you get any solution?

thanks

amirgee007's avatar

using your solution but same it showing pages with base URL, not with exact URLs.

gogilo's avatar

This was helpful. Just remember to import these classes before hand

use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

for simplePaginate() you can do

if (!Collection::hasMacro('simplePaginate')) {

    Collection::macro('simplePaginate', 
        function ($perPage = 15, $page = null, $options = []) {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        return (
            new Paginator(
                $this->forPage($page, $perPage), 
                $perPage, 
                $page, 
                $options
            )
        )->withPath('');
    });
}
3 likes
panduananto's avatar

@gogilo hey, when i implement this function, its like my data just got cut off. for example I have 5 data and I paginate to 3 and its just returning 3 data and I don't get the rest of the data. when I do like {{$comments->hasMorePages()}} in the view, it is returning false where it should return true because I should have 2 more data. any clue why this is happening?

progalaa's avatar

After adding Paginate() to your eloquent result or your repository you'll get data paginated and you can show your pagination details in resource :

To make your code clean make a PaginationResource to be used across different collections and make single place for editing pagination details

then inside any resource add your Pagination resource as follow

this is Pagination resource

public function toArray($request) : Array
    {
        return [
            'total' => $this->total(),
            'count' => $this->count(),
            'per_page' => $this->perPage(),
            'current_page' => $this->currentPage(),
            'total_pages' => $this->lastPage()
        ];
    }

and add it to any other collection like this

 public function toArray($request) : Array
    {
        $pagination = new PaginationResource($this);

        return [
            'templates' => $this->collection,
            $pagination::$wrap => $pagination,
        ];
    }

3 likes
furqanDev's avatar

@maliksajid Answer is well explained. This gist is well written and explained. If you are still stuck then go read this gist.

1 like
projectasphaliea's avatar

I've been using this gist and it works beautifully: https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

I am currently using a 3rd party API and decided to go with this route: https://laravel-news.com/working-with-third-party-services-in-laravel

The API I'm using needs the params per_page and page for pagination:

E.g: https://this-is-my-api-domain/api/v2/products?per_page=10&page=20

Is there however a "simple" way to send the perPage/page attributes from the paginate() method to somewhere else ? Currently it works by doing

$this->users->list()->paginate(2)

And it will paginate everything from https://this-is-my-api-domain/api/v2/products

But I would love to automatically append the per_page and page attributes to the API url and have this or another package generate the links for it like Laravel does.

Please or to participate in this conversation.