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:

    ->select('*', DB::raw('COUNT(*) as products_count'))
    ->having('products_count', '>' , 1)


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.


#laravel #query-builder #query #having #havingraw #dbraw #groupby