Skip to main content
Tutorial Free

Did you know about havingRaw() function?

September 22, 2015
1 min read
Eloquent and Query Builder have a lot of "hidden gems" which are not in the official docs. For example, if you want to perform GROUP BY and HAVING, there's a little trick for unnamed columns. Let's say you want to filter all product categories with more than one products - which means write this query in Eloquent:
SELECT *, COUNT(*) FROM products GROUP BY category_id HAVING count(*) > 1
Basically, it's simple - you would just use groupBy() and having() functions, right? But we don't have the column name for having. Of course, we can assign it, and with Query Builder write something like:
DB::table('products')
    ->select('*', DB::raw('COUNT(*) as products_count'))
    ->groupBy('category_id')
    ->having('products_count', '>' , 1)
    ->get();
But there's a shorter way - there's a function havingRaw():
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
You can add your wanted columns into select(), but essentially that's a shortcut I wanted to briefly show you.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses on Laravel Daily

Roles and Permissions in Laravel 13

14 lessons
57 min

How to Build Laravel 13 API From Scratch

30 lessons
1 h 23 min

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

No comments yet…