laravel group by 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 not in query

DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();

Example 3: 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 4: groupby in laravel

You can use unique('field_name'); instead of groupBy('field_name');
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $messages = Message::select("*")
                            ->where('receiver_id',$id)
                            ->orderBy('created_at', 'desc')
                            ->get()
                            ->unique('sender_id');
  
    dd($messages);
}

Example 5: when in larevel

$role = $request->input('role');

$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();

Tags:

Php Example