MahmoudAdelAli's avatar

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)
0 likes
3 replies
LaryAI's avatar
Level 58

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:

$labelsCount = Label::latest()->count();
$labels = Label::latest()->paginate(25);
1 like
webrobert's avatar

@MahmoudAdelAli,

hmmm. not sure what else you are doing there. but if you have a paginate instance.

and you call its method total()

it wont make additional queries to the database

$labels = Label::latest()->paginate(25)

then

$labels->total();

EDIT: for clarity, it makes one for the count (so it can paginate I assume) and one for the results whether you call total or not

Please or to participate in this conversation.