ItSolutionStuff.com

Laravel Groupby Having with DB::raw() Example

By Hardik Savani • April 16, 2024
Laravel

We most probably require to use group by having because if you work on small project then it's not need to use generally. But if you work with big project like e-commerce, social or ERP level project then you may require to use having clause.

you can also use groupby having with db raw in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 app.

having clause, we can use simply if we have to compare with number or static value like as bellow:

->having("total_quantity","<",10)

But we need to compare with 10 instead of column name then it can't directly use column name. At that time we should use DB::raw() with column name.

In this example i want to show minimum quantity items, I have two tables one items and another one items_count both mysql table layout is here:

items table:

items_count table:

I need to get that product has less quantity to min_quantity of items table, so we check get that items using bellow query:

Example

$items = DB::table("items")

->select("items.id","items.title"

,"items.min_quantity"

,DB::raw('SUM(items_count.quantity) as total_quantity'))

->join("items_count","items_count.id_item","=","items.id")

->groupBy("items.id")

->having("total_quantity","<",DB::raw("items.min_quantity"))

->get();

print_r($items);

You will find bellow output get only items no. 2.

Array

(

[0] => stdClass Object

(

[id] => 2

[title] => Itsolutionstuff.com

[min_quantity] => 10

[total_quantity] => 5

)

)

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Where Clause with Function Query Example

Read Now →

How to Get Last Executed Query in Laravel 9?

Read Now →

Laravel Sum Query with Where Condition Example

Read Now →

Laravel Eloquent whereHas() Condition Example

Read Now →

Laravel Case Sensitive Query Search Example

Read Now →

How to Select Custom Column with Value in Laravel Query?

Read Now →

Laravel Eloquent Group By Year with Sum Example

Read Now →

Laravel Eloquent updateOrCreate Example

Read Now →

Laravel Eloquent Order By Query Example

Read Now →

Laravel Groupby Having with DB::raw() Example

Read Now →

Laravel Group By with Month and Year Example

Read Now →

Laravel Eloquent Group By with Multiple Columns Example

Read Now →

Laravel Select with Count Query with Group By Example

Read Now →