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

 

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

In Laravel Eloquent, you can use the groupBy method to group records based on specific columns and the count method to return the number of records in each group. Here's an example:

$users = User::select('name', \DB::raw('count(*) as total'))
             ->groupBy('name')
             ->get();

This will retrieve all the User records and group them by the name column. The select method is used to specify the columns to be retrieved, and the \DB::raw method is used to specify a raw expression (in this case, a count of the number of records in each group). The resulting collection will contain one record for each group, with the name column and a total column that contains the number of records in each group.

Previous Post Next Post

Contact Form