How to Use groupBy() having() and havingRaw() with DB::raw in Laravel ?

Sometimes we need to write query with group by having in laravel. If you work with small application then it's no need to use them. But in large scale project like e-commerce we need to use that kind of query like you may require to use having clause.

If you want to perform with GROUP BY and HAVING, there’s a little trick for unnamed columns. Let assume you need to filter all product categories with more than one products – How you can write this query using Group by and having?

It is not hard to write this query. Generally you would just use groupBy() and having() functions, So the ultimate query will look like this:

DB::table('products')
    ->select('*', DB::raw('COUNT(*) as products_count'))
    ->groupBy('category_id')
    ->having('products_count', '>' , 1)
    ->get();

 

That's all. But we can still optimized this query using havingRaw() functions. You know that there’s a shorter way – there’s a function havingRaw():

Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();

 

Hope it can help you.