简体   繁体   English

使用分页获取结果总数

[英]Get total number of results with pagination

I'd like to get the total number of users on a page where all the users are listed.我想在列出所有用户的页面上获取用户总数。 This page should be paginated.这个页面应该分页。

So far, this is what I've come up with:到目前为止,这就是我想出的:

Controller控制器

$users = User::paginate(10);
return View::make('index', compact('users'));

View:看法:

{{{ count($users) }}}

But this gives me only the count of the users for the current page.但这只给了我当前页面的用户数。 I'd like to count the full result set, if possible without querying another time the database.如果可能,我想计算完整的结果集,而无需再次查询数据库。

In Laravel 4 use:在 Laravel 4 中使用:

{{ $users->getTotal() }}

Docs文档


In Laravel 5 and above use:在 Laravel 5 及以上版本中使用:

{{ $users->total() }}

Docs文档

Controller控制器

$products = ProductMaster::paginate(10); //1 page with 10 products

return view('index',compact('products'));

view看法

 {{ $products->total() }}   //show total products in your database

To Get All Item Total获取所有项目总数

$paginator->total() Determine the total number of matching items in the data store. $paginator->total()确定数据存储中匹配项的总数。 (Not available when using simplePaginate). (在使用 simplePaginate 时不可用)。

To Get Current Page Total获取当前页面总数

$paginator->count() Get the number of items for the current page. $paginator->count()获取当前页面的项目数。

Example例子

Controller控制器

$users = User::paginate(10); //1 page with 10 products
return view('users', compact("users"));

View:看法:

{{ $users->total() }} //show total users in your database

On Laravel 8x this data is also returned in the response.在 Laravel 8x 上,此数据也会在响应中返回。

https://laravel.com/docs/8.x/pagination#introduction https://laravel.com/docs/8.x/pagination#introduction

The JSON from the paginator will include meta information such as total, current_page, last_page, and more.来自分页器的 JSON 将包含元信息,例如 total、current_page、last_page 等。 The result records are available via the data key in the JSON array.结果记录可通过 JSON 数组中的数据键获得。 Here is an example of the JSON created by returning a paginator instance from a route:以下是通过从路由返回分页器实例创建的 JSON 示例:

{
   "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":[
        {
            // Record...
        },
        {
            // Record...
        }
   ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM