Čamo
Čamo

Reputation: 4172

Laravel 5.7 Collection get size and offset after pagination

I have a paginated collection like

Post::where('active', 1)->paginate(10)

and I would like to get the start and end position of the current portion of collection. I mean if page is 2 and page limit is 10 then the start position is 11 and end position is 20. I need to render a text like products from 11 to 20 of total 284 products. Is it possible or not?

Upvotes: 2

Views: 778

Answers (1)

Remul
Remul

Reputation: 8252

The following methods will return the information you want:

$pagination = Post::where('active', 1)->paginate(10);

$pagination->firstItem(); // Returns the number of the first item from the current page

$pagination->lastItem(); // Returns the number of the last item from the current page

$pagination->total(); // Returns the total amount of items

You can find all available methods here.

If you convert the pagination into an array or JSON it will automatically add all the meta information.

From the docs:

The JSON from the paginator will include meta information such as total, current_page, last_page, and more. The actual result objects will be available via the data key in the JSON array. Here is an example of the JSON created by returning a paginator instance from a route:

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}

Upvotes: 1

Related Questions