RonaldGJ's avatar

Get all with count of specific condition.

Hi there,

Is it possible to make 1 query to get all results, and also a count of a specific condition.

I'm now using this code to take all subscribers: $subscriptions = Subscription::with('participants')->get();

And then in de template view I use: {{ $subscriptions->count() }}

But I also want to show the count of all the subscribes who has paid. So: {{ $subscriptions->paid()->count() }}

Thank you!

Ronald.

0 likes
8 replies
Drfraker's avatar
Drfraker
Best Answer
Level 28

If you want to stick to depending on the subscriptions collection, you should be able to do something like:


$subscriptions->filter(function($subscription){
    return $subscription->paid();
})->count();

It might be better to move this logic out of the view though.

1 like
ovvessem's avatar

One option would be to have 2 query's. Another option would be to make use of DB::raw() - https://laravel.com/docs/5.5/queries

$select = DB::raw(
'COUNT(*) AS total
, COUNT(CASE status WHEN "paid" THEN 1 ELSE NULL END) AS paid
');

$metrics = DB::table('subscriptions')->select($select);
1 like
RonaldGJ's avatar

@ovvessem Nice! Now I get both count returned right? I actually want a list with all subscriptions. And a count of the subscriptions with a paid status of 1.

ovvessem's avatar

@RonaldGJ Yes, with the raw query you would get the total counts for both conditions. If you want the list in combination with the total count then the raw statement is not what you are looking for.

More suitable approach would be the suggestion @Drfraker gave. To confirm it will not run a new query against the database. If you are curious which query's are executed you could use of one of the following packages:

Drfraker's avatar

@RonaldGJ That is correct, it will not run another query. Once you call the get() method on query you get an eloquent collection. So manipulation of that data is not hitting the database anymore.

RonaldGJ's avatar

@ovvessem Thank you! I was already looking for those packages, but I couldn't find them. I'll use the solution of @Drfraker

Thank you both for your replies!

Please or to participate in this conversation.