ivanhalen's avatar

Count from/to records in pagination

Hello, When using pagination I an easily show the total records:

Total Records: {{ $results->total() }}

But what if I want to show something like this?

Records 1-10 of {{ $results->total() }} (for page 1)
Records 11-20 of {{ $results->total() }} (for page 2)
Records 21-30 of {{ $results->total() }} (for page 3, and so on)

etc.? Thanks

0 likes
5 replies
jhoff's avatar

The paginate() method returns all of that data for you:

{
    total: 1000,
    per_page: 15,
    current_page: 1,
    last_page: 67,
    next_page_url: "https://example.com/foo/?page=2",
    prev_page_url: null,
    from: 1,
    to: 15,
    data: [...]
}

So you should be able to do something like this:

$results = MyModel::paginate(15);
...
Records {{ $results->from }} - {{ $results->to }} of {{ $results->total }} (for page {{ $results->current_page }} )
3 likes
thomaskim's avatar
Level 41

@ivanhalen Instead of from or to, use $results->firstItem() and $results->lastItem().

2 likes
jhoff's avatar

@ivanhalen, Your error message might indicate that $results is a Collection not a LengthAwarePaginator. There might be an issue there.

If $results comes directly from Model::paginate(), you should be able to use any of the LengthAwarePaginator methods.

Records {{ $results->firstItem() }} - {{ $results->lastItem() }} of {{ $results->total() }} (for page {{ $results->currentPage() }} )

Check out http://laravel.com/docs/5.1/pagination#displaying-results-in-a-view or the toArray method in Illuminate\Pagination\LengthAwarePaginator.php for some other common pagination methods.

Also, I apologize for the initial confusion. I've been using a lot of vue.js lately, so I'm used to pagination being returned as JSON. The from and to properties I refrenced can be found in the documentation here: http://laravel.com/docs/5.1/pagination#converting-results-to-json

6 likes
ivanhalen's avatar

Thanks both, it works with firstItem() and lastItem(): just a bit mad that these methods were not mentioned in the docs!

Please or to participate in this conversation.