Laravel 5.7 集合在分页后获取大小和偏移量

Laravel 5.7 Collection get size and offset after pagination

我有一个像这样的分页集合

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

我想获取当前集合部分的开始和结束位置。 我的意思是,如果页面是 2,页面限制是 10,那么起始位置是 11,结束位置是 20。我需要渲染一个文本,比如 284 种产品中的 11 到 20 种产品。可不可以?

以下方法将return您想要的信息:

$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

您可以找到所有可用的方法here

如果您将分页转换为数组或JSON它会自动添加所有元信息。

来自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
        }
   ]
}