Pagination is a bit confusing

Doing:

await Post.query()
          .orderBy('id', 'desc')
          .paginate(5)

returnns something like:

"total": 10,
"perPage": 20,
"page": 5,
"lastPage": 1,
"data": []

The perPage is wrong (it defaults to 20) which is supposed to be 5 in my case. But if I do:

await Post.query()
          .orderBy('id', 'desc')
          .paginate(1, 5)

Then I get:

"total": 10,
"perPage": 5,
"page": 1,
"lastPage": 2,
"data": [...]

which works as expected. From the response, what is page supposed to be?

1 Like

The 1st argument to the paginate method is the page for which you want to fetch results and 2nd is the limit.

paginate(1, 20) -> Page 1, Limit 20
paginate(5, 20) -> Page 5, Limit 20
1 Like

Sorry, I don’t get this part.

So pagination works with a page and a limit right. For example you have 100 results and want to show 10 results/page.

So it will be page : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

Now everytime you call paginate method, you have to pass for which page you want to fetch results for.

paginate(page, limit)

So I need to dynamically pass page to paginate to get the current page?

Maybe you are confusing it with something else

How do u expect pagination to work?

What I was expecting was doing something like paginate(20) will display 20 items per page with links to subsequent pages so there are enough items.

and how are you expecting to get the 20 items for the second page?

The paginate method will get the total number of items then chunk them into 20 items per page. If the total number of items is less than 20, then it displays them in just one page. But the total number of items is greater than 20, then there will be link to next page with the remaining items.

Taking Laravel’s paginate() for example, I only need to supply the number of items I want displayed per page.

Yes, but how your pagination will know that you are on page 2 and you need the next 20 items?

This is why you need to provide to the paginate method the page you are currently on and the number of item you want to have per page.

Model.paginate(1, 20) // I'm on page 1 and I want 20 items per page
Model.paginate(2, 20) // I'm on page 2 and I want 20 items per page

Then you decide how you want to provide this value, a lot of people are using query string like example.com/articles?page=2.

I get that and that was why I asked :point_down:

not 100% sure
but i think it works like

paginate(1,20) give first 20
paginate(2,20) skip 20 and give me the next
paginate(3,20) skip 40 and give me the next

Thanks guys! Got it figured out.

This is really confusing, when I try to use .paginate() at the end of my query the record shows undefined on my .edge file. But when I remove the .paginte() and replace it with .fetch it works perfectly.
What do you guys think is the problem with it?

Please don’t bother to answer this, I finally got the answer