thebigk's avatar
Level 13

Pagination: How to get total number of pages?

I'm curious to know what's the right way to get the total number of pages when we use "Pagination". I want to display : Viewing Page 3 of 335.

PS: I'm surprised that there is no direct way of getting this count.

0 likes
8 replies
thebigk's avatar
Level 13

$results->count() => Get the number of items for the current page.

This gives me how many items are there on the current page. I want the total number of pages.

Nakov's avatar

@thebigk okay, there are other methods :)

$results->total() - Determine the total number of matching items in the data store. (Not available when using simplePaginate).

thebigk's avatar
Level 13

I really appreciate your responses; but that too isn't what I want. Results $results->total() gives me the total number of records, not pages in paginator.

For example, let's say I have 100 records and if I :

  1. Paginate at 10 rows; I will get 10 pages
  2. Paginate at 5 rows; I will get 20 pages

I'm interested in getting pages count.

Nakov's avatar

@thebigk using the methods, here is the total number of pages, a bit of a math :)

dd((int) ceil($results->total() / $results->perPage()));
jlrdw's avatar

Or Taylor has also done the simple math for you

$results->lastPage();

So in your example 2 above, would be 20.

Not available when using simplePaginate. Also, if using lengthaware you have to do some simple math yourself.

https://laracasts.com/discuss/channels/guides/manual-pagination-episode-3

https://laravel.com/docs/6.x/pagination#paginator-instance-methods

I just noticed, @thebigk when @nakov gave you the link to the paginator-instance-methods, you should have seen for yourself that lastPage is also the same as the number of pages.

Nakov's avatar

@jlrdw good point. Didn't noticed the method myself :) Thanks.

Please or to participate in this conversation.