laravel with groupby code example
Example 1: group by laravel
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->get();
Example 2: groupby in laravel
You can use unique('field_name'); instead of groupBy('field_name');
public function index()
{
$messages = Message::select("*")
->where('receiver_id',$id)
->orderBy('created_at', 'desc')
->get()
->unique('sender_id');
dd($messages);
}
Example 3: laravel collection group by
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();