How to count collection pagination without duplicated queires
Hi , i have a data and i paginate it like that
'labels' => Label::latest()->paginate(25),
and i count it using
$labels->count() // Or total()
but the queries is duplicated to get count
select count(*) as aggregate from `labels`
select * from `labels` order by `created_at` desc limit 25 offset 0
select count(*) as aggregate from `flags`
select * from `flags` order by `created_at` desc limit 25 offset 0
select count(*) as aggregate from `client_types`
select * from `client_types` order by `created_at` desc limit 25 offset 0
select count(*) as aggregate from `document_types`
select * from `document_types` order by `created_at` desc limit 25 offset 0
select * from `labels` where `labels`.`id` in (2, 3)
Instead of using $labels->count() or $labels->total(), you can use $labels->count() method on the underlying collection. This will not execute a separate query to count the total number of items in the collection. Here's an example:
$labels = Label::latest()->paginate(25);
$labelsCount = $labels->count(); // This will not execute a separate query
Alternatively, you can use the count() method on the query builder instance before calling paginate() method. This will count the total number of items in the query without executing a separate query. Here's an example: