Skip to main content
Tutorial Free

Eloquent: shorter WHERE clauses with whereField

August 20, 2015
1 min read
There's one really neat Laravel Eloquent function which, from my experience, a lot of developers don't know. How do we write WHERE clauses on Eloquent queries? First option: with three arguments - field, operator, value.
$products = Product::where('category', '=', 3)->get();
Shorter option: we can skip the second parameter, equal sign.
$products = Product::where('category', 3)->get();
But now - even shorter option: did you know you can do THAT?
$products = Product::whereCategory(3)->get();
Yes, exactly, just add your field in CamelCase after the where symbols. Under the hood Laravel engine will transform it into a proper where clause with equal sign. And if you have a field with more than one "word" and underscore separator, like category_id - transform it into CamelCase:
$products = Product::whereCategoryId(3)->get();
That's it, simple "trick" but the code is even more readable now, isn't it?

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

Testing in Laravel 13 For Beginners

26 lessons
1 h 41 min read

Queues in Laravel 13

18 lessons
1 h 12 min read

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

No comments yet…