Support the ongoing development of Laravel.io →
posted 5 years ago
Last updated 1 year ago.
0

I don't think you understand what the builder does. $customers = Customer::query() doesn't query the database, it generates a new query builder instance. Only when you finally call ->get() or ->paginate() or even ->count() etc. will the database actually be queried.

Not knowing your specific use case I can only guess that you actually do want to query the database twice, once to get active customers and once to get premium customers which is totally normal.

If you use the same query builder and instance and call ->active() and ->premium() you are actually saying "Get all customers where active and premium".

0

Yeah, I understand that it generates a new query builder instance. What I want to do is count the number of active() and premium() customers in one database query not two.

0

OK, so you probably want to query the database without any conditions or only conditions that will return you a dataset with both premium and active records. You can then use Laravel collection methods to count based on condition - https://laravel.com/docs/5.7/collections#method-where

E.g. $customers = Customer::all() or $customers = Customer::where('active',true)->orWhere('premium',true)->get();

$active = $customers->where('active', true)->count(); $active = $customers->where('premium', true)->count();

0

Thank you @ashg. I would try this.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.