Reputation: 2310
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.
Upvotes: 45
Views: 96090
Reputation: 302
Get the total, current page, perpage etc.
$total = $users->total();
$currentPage = $users->currentPage();
$perPage = $users->perPage();
$from = ($currentPage - 1) * $perPage + 1;
$to = min($currentPage * $perPage, $total);
echo "Showing {$from} to {$to} of {$total} entries";
Upvotes: 6
Reputation: 748
for total results {{ $results->total() }}
for the first item of current page {{ $results->firstItem() }}
for the last item of current page {{ $results->lastItem() }}
for current page {{ $results->currentPage() }}
Upvotes: 0
Reputation: 153140
In Laravel 4 use:
{{ $users->getTotal() }}
In Laravel 5 and above use:
{{ $users->total() }}
Upvotes: 132
Reputation: 11
On Laravel 8x this data is also returned in the response.
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. The result records are 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":[
{
// Record...
},
{
// Record...
}
]
}
Upvotes: 0
Reputation: 345
To Get All Item Total
$paginator->total()
Determine the total number of matching items in the data store. (Not available when using simplePaginate).
To Get Current Page Total
$paginator->count()
Get the number of items for the current page.
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
Upvotes: 8
Reputation: 804
Controller
$products = ProductMaster::paginate(10); //1 page with 10 products
return view('index',compact('products'));
view
{{ $products->total() }} //show total products in your database
Upvotes: 8