php

Laravel Eloquent groupBy() AND also return count of each group

Problem

I have a table that contains, along with other columns, a column of browser versions. And I simply want to know from the record-set, how browsers exist, from those that visited my website. So, I need to end up with something like this: Total Records: 10; Internet Explorer 8: 2; Chrome 25: 4; Firefox 20: 4. (All adding up to 10)

Here’s my two pence:

$user_info = Usermeta::groupBy('browser')->get();

Naturally, that just provides the 3 browsers and not the number of each. How do I do this?

Solution

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

About the author

laravelrecipies