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

karrar's avatar

Multiple query on one instance

Hello guys!

In my case , I need to return this data from model :

1- list of pagination users

2- count all users

3- count active users

4- count inactive users

my query looks like:

$userModel = User::query();

return Inertia::render('Home', [

'users' => $userModel->paginate(), // list of users

'total_users' => $userModel->count(), // 10

'active_users' => $userModel->active()->count(), // 5

'inactive_users' => $userModel->inactive()->count() // 0

]);

and the active/inactive scope looks like :

public function scopeActive($query)

{

         $query->where('status', UserStatus::Active->value);
}

The problem is :

any query after active_users will return 0. like inactive_users always return 0 .

How can I achive that without create new instance from User model.

Thanks.

0 likes
6 replies
tykus's avatar
tykus
Best Answer
Level 104

You need to clone the query because the active scope is mutating the query Builder instance:

'active_users' => $userModel->clone()->active()->count(), // 5
'inactive_users' => $userModel->clone()->inactive()->count() // 0
karrar's avatar

@tykus I already clone the object but I ask here if there is another better solution. thank you.

tykus's avatar

@karrar you didn't show anywhere that you cloned it ¯\_(ツ)_/¯

Anyway, you need a clean query Builder instance without constraints imposed by the earlier expressions on the same instance. This is achieved by cloning the original instance.

1 like
pkboom's avatar

After you called $userModel->active()->count(), the query get to have this condition(status=active).

So after this, when you call $userModel->inactive()->count(), its query would look like this.

... users where status = active and status = inactive ...

You can remove where clause like this: $query->wheres = [].

tykus's avatar

@pkboom modifying the wheres property only is possible on the Base Query instance; there is no wheres on the Eloquent Builder!

Please or to participate in this conversation.