how to get the data of groupBy and the count in Laravel?

Viewed 172

How to get the count of groupBy and also the data?

I've tried this one but it only returns the count, without the data.

$data = Model::orderBy('id', 'desc')
                ->select('status', DB::raw('count(*) as total'))
                ->groupBy('status')
                ->get();

Any help would be appreciated,

Thanks

1 Answers
$data = Model::orderBy('id', 'desc')
                ->selectRaw('id, status, count(*) AS count')
                ->groupBy('status')
                ->get();

Haven't tested. It will be something like this. This will return an array with id, status and count. If it doesnt work let me know.

but if you including id which is unique and does not make sense in a groupby this way, your mysql should be enabled to do so, otherwise it will throw sql_mode=only_full_group_by error laravel. It can handled by changing the mode. but I would recommend removing the order by id.

'connections' => [
    'mysql' => [
        // Behave like MySQL 5.6
        'strict' => false,

        // Behave like MySQL 5.7
        'strict' => true,
    ]
]
Related