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".
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.
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();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community