group by in laravel query builder code example
Example 1: group by laravel
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->get();
Example 2: laravel group by with where clause
$groupedSalesCampaign = Order::with('Campaign')
->where('isapproved','=','Y')
->groupBy('campaign_id')
->orderBy(DB::raw('COUNT(id)','desc'))
->get(array(DB::raw('COUNT(id) as totalsales'),'campaign_id'));
Example 3: 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);
}