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

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:

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

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:

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);

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.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →