See total records in Laravel

Asked

Viewed 2,630 times

4

In certain part of my application written in Laravel I have this consultation:

$counts = User::select(\DB::raw('count(*) as status_count, status'))
                    ->groupBy('status')
                    ->get();

It returns me at least 1 record and at most 3, these are exactly the existing status. How do I return an extra line containing the total of records?

2 answers

5


Make another select. It’s the simplest solution in this case.

$counts = User::select(\DB::raw('count(*) as status_count, status'))
                    ->groupBy('status')
                    ->get();

$total_counts = User::count();

To avoid a second query, then it is possible to use the method sum of Eloquent\Collection.

 var_dump($counts->sum('status_count'));
  • 1

    Thanks friend, however, I was trying to avoid an extra consultation. For this I used Rafael’s suggestion

  • I edited the answer. Actually his solution is good, but you’d be remaking something Laravel has already done internally. The method Collection::sum already makes a Collection::reduce internally.

  • Nice. Thank you very much

4

If you choose not to make another select, you can use the reduce method from Collection, for example:

$total = $counts->reduce(
    function ($carrier, $item) {
        return $carrier + $item->status_count;
    }, 0
);

Any doubt of a look at documentation.

  • 1

    Ball show, my goal was just not to perform an extra consultation.

  • If that’s the case, then I didn’t need the reduce, I know a simpler way :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.