Check total records in Laravel

4

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

$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 just the existing status. How do I return an extra line containing the total of records?

    
asked by anonymous 23.06.2016 / 06:23

2 answers

4

Make another select. It is 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, you can then use the sum method of Eloquent\Collection .

 var_dump($counts->sum('status_count'));
    
23.06.2016 / 13:26
4

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

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

Any questions at documentation .

    
23.06.2016 / 13:45