Home Laravel How to use groupby having with DB::raw in Laravel ?

How to use groupby having with DB::raw in Laravel ?

by Shahriar Sagor

Today now in this post i will show you How to use groupby having with DB::raw in Laravel Query Builder? Most of times we probably need to use the group by having because if we are work on the small project then it’s not need to use this generally. But if when we are working with any big project as like e-commerce, social blogging site or any ERP level project then we must need to use the having clause.

We can also use the groupby having also with the db raw in any version of laravel such as ; laravel 6, laravel 7 and laravel 8 application.

By using having clause, we can use the simply if we need to compare with the number or static value as like as bellow:


But when we required to compare with the 10 instead of column as name then it can’t be directly by use column name. So At that time we must need to use DB::raw() with column name.

Now in this example i will show you the minimum quantity items, so I have two tables one is items and another one is items_count.

So now i need to get that product what has less quantity to the min_quantity of items table, so here we will check how to get that items by using the bellow query:

$items = DB::table("items")
                ,DB::raw('SUM(items_count.quantity) as total_quantity'))

Read Also : How to Create Custom Blade Directive in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook.


You may also like