Laravel Eloquent groupBy () And also returns the amount of each group

I have a table that contains, among other columns, a browser version column. And I just want to find out from the recordset how many each type of browser has. So, I need in the end something like this: Total Records: 10; Internet Explorer 8: 2; Chrome 25: 4; Firefox 20: 4. (All with the addition of up to 10)

Here are my two pence:

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

Of course, these are just three browsers, not the number of each. How can i do this?

+67
eloquent laravel laravel-4
Aug 30 '13 at 12:35
source share
8 answers

This works for me:

 $user_info = DB::table('usermetas') ->select('browser', DB::raw('count(*) as total')) ->groupBy('browser') ->get(); 
+133
Aug 30 '13 at 13:11
source share

This works for me (Laravel 5.1):

 $user_info = Usermeta::groupBy('browser')->select('browser', DB::raw('count(*) as total'))->get(); 
+21
Jul 20 '16 at 10:00
source share

Thanks Antonio

I just added the lists command to the end, so it will return only one array with the key and counter:

Laravel 4

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

Laravel 5.1

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

Laravel 5.2 +

 $user_info = DB::table('usermetas') ->select('browser', DB::raw('count(*) as total')) ->groupBy('browser') ->pluck('total','browser')->all(); 
+15
Aug 11 '15 at 15:34
source share

It works the same way, a little more neatly. getQuery() simply returns a base constructor that already contains a table reference.

 $browser_total_raw = DB::raw('count(*) as total'); $user_info = Usermeta::getQuery() ->select('browser', $browser_total_raw) ->groupBy('browser') ->pluck('total','browser'); 
+8
Nov 12 '15 at 16:08
source share

If you want a collection, groupBy and count:

 $collection = ModelName::groupBy('group_id') ->selectRaw('count(*) as total, group_id') ->get(); 

Hurrah!

+2
Aug 17 '18 at 8:42
source share
  1. Open config/database.php
  2. Find strict key in mysql connection settings
  3. Set the value to false
+2
Aug 27 '18 at 10:58
source share

Here's an easier way to process a Laravel group without using raw operators.

 $sources = $sources->where('age','>', 31)->groupBy('age'); $output = null; foreach($sources as $key => $source) { foreach($source as $item) { //get each item in the group } $output[$key] = $source->count(); } 
+1
Mar 28 '18 at 22:24
source share

Try with this

 ->groupBy('state_id','locality') ->havingRaw('count > 1 ') ->having('items.name','LIKE',"%$keyword%") ->orHavingRaw('brand LIKE ?',array("%$keyword%")) 
0
Dec 07 '17 at 11:11
source share



All Articles