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?
> That’s it, simple “trick” but the code is even more readable now, isn’t it?
I can’t agree with you. In your opinion – code may be more readable, but the same code isn’t testable. Each call of magic method sounds like problem for unit tests.
Pomek, agree on that – magic methods don’t help with unit tests. So, guys, use with caution.
I’m not sure one needs to test whether a SQL statement was constructed correctly, but needs to test whether the results returned are good.
If you’re mocking models to test functionality provided by Laravel, then you’re testing too low IMO.
Toca refactorizar
Povilas, good tip by the way.
This could cause some problems with IDE’s
You’re right, PHPStorm has issues with them too, even using packages to generate metadata.
How about $query->where(‘amount’, ‘<', 5);
Can it be shortened if you're not using = operator?
Hi Dave, from what I know it’s not possible.
Wow. So irritating functionality. Why not add something like that:
– whereSomeFieldIsGreaterThan(value),
– whereSomeFieldIsGreaterOrEqualThan(value),
– whereSomeFieldIsLesserThan(value),
– whereSomeFieldIsLesserOrEqualThan(value)
and then parse everything from the method name.
IMHO it’s completely unnecessary syntactic sugar. Method name is a method name, not some kind of an expression. Maybe it’s a little more readable but only for some fresh junior developer. For regular developer it’s misleading and confusing.
It’s worth knowing something like this exists but I would strongly advise to avoid it completely.
(Sorry for my English. I hope it’s understandable)