The following example will give me all users that are older than $age
and have the gender $gender
:
public function get_users_older_than(int $age = null, string $gender = null) {
$users = User::query()
->where('age', '>', $age)
->where('gender', $gender)
->get();
return $users;
}
Is there a way to use the where clause only if age or gender is present in a more eloquent and shorter way then:
public function get_users_older_than(int $age = null, string $gender = null) {
$users = User::query();
if ($age) {
$users = $users->where('age', '>', $age):
}
if ($gender) {
$users = $users->where('gender', $gender):
}
$users = $users->get();
return $users;
}
With that, I could avoid to create and use the extra function and just have one single arrow connected line of code.
2
Answers
A shorter way to do that would be this:
But just so you know, shorter code does not guarantee more efficiency.
There is also a conditional clauses function
when
.Based on what you have, that could look like: