Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

guido_manta's avatar

Combining withCount() and Where Clauses

Hi! Is there a way to retrieve the relation+'_count' column from withCount() function and use it with where clauses?

For example, I have a class named Groups. Each Group has many Contacts. Using withCount() function, I can get the number of Contacts owned by a Group and store it into the 'contacts_count' column. Now I want to retrieve this value and use to make, for example, a call like $query->where('contacts_count', '>', '100'); How can I do it?

0 likes
4 replies
SaeedPrez's avatar
$result = App\Group::withCount('contacts')->has('contacts', '>', 100)->get();
guido_manta's avatar

Ok, and what if I have

$result = App\Group::withCount('contacts');

and want to pass $result to another function which calls:

$result->where('contacts', '>', 100);

I get an SQL error 'cause in fact 'contacts' column doesn't exist in my DB. How can I do that?

SaeedPrez's avatar
Level 50

Look at the query I provided again, contacts is not a column name, it's the relationship method name. Which is why I'm using has() and not where()

Please or to participate in this conversation.