Tominator's avatar

Pagination with a maximum limit

Hi,

I'm trying to create a "recent products" page, with a paginator.

My naive attempt is Product::(somefilters)->paginate(10);

This works well, as in it paginates nicely in the view. However, it takes all products in my database that match the filters. For my "recently added" section, I'd like to return a maximum of 100 products, not however many were created in the last x days.

Adding a ->take(100) in my somefilters section doesn't help, because the paginate() method overrides that to provide its pagination.

What would be the best way to go?

0 likes
2 replies
shez1983's avatar

one way would be to just add a where clause that gets products which were created in the last x many days?

else you will have to create your own manual pagination (refer to docs, its not that hard)

Tominator's avatar

With the where clause, I would still get a variable number of products, so I'd like to avoid that.

Creating my own pagination is not that well explained in the docs I find. "You may do so by creating either an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance", but where do I create that? Do I make a new method on my Product model? Like ->myCustomPagination()? Is there a better place, a custom class?

Also, is the working then that I first do Product::(somefilters)->take(100)->get(), thereby getting the full data in my memory, and then put it in that myCustomPagination method?

Please or to participate in this conversation.