DEV Community

Morcos Gad
Morcos Gad

Posted on • Updated on

Laravel ( WhereRaw HavingRaw OrderByRaw SelectRaw whereNotNull And whereNull )

Let's get started quickly We start with WhereRaw

$products = DB::table('products')
             ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
             ->get();
Enter fullscreen mode Exit fullscreen mode

havingRaw

Product::groupBy('product_id')->havingRaw('COUNT(*) > 1')->get();
Enter fullscreen mode Exit fullscreen mode

orderByRaw

User::where('created_at', '>', '2022-01-01')
    ->orderByRaw('(updated_at - created_at) desc')
    ->get();
Enter fullscreen mode Exit fullscreen mode

Eloquent selectRaw()

User::select("*")
     ->selectRaw('amount + ? as amount_with_bonus', [500])
     ->get();
Enter fullscreen mode Exit fullscreen mode

Another example

User::select("*")
    ->select('*', DB::raw('amount + 500 as amount_with_bonus'))
    ->get();
Enter fullscreen mode Exit fullscreen mode

Eloquent whereNotNull()

select * from `users` where `email_verified_at` is not null
Enter fullscreen mode Exit fullscreen mode
User::select("*")
      ->whereNotNull('email_verified_at')
      ->get();
Enter fullscreen mode Exit fullscreen mode

Eloquent whereNull()

select * from `users` where `email_verified_at` is null
Enter fullscreen mode Exit fullscreen mode
User::select("*")
      ->whereNull('email_verified_at')
      ->get();
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Discussion (0)