Dynamic Where Clauses in Laravel Eloquent

By Michael Williams, Published on 04/24/2018

One of the many features that doesn't appear to be widely discussed regarding Eloquent, is the ability to use dynamic information in the where clauses.

Assuming that you have a Users model and want to retrieve a result based on email. It's known that you can query the database as such:

return $this->users->where('email', '[email protected]')->first();

Did you know that you could also write the query as:

return $this->users->whereEmail('[email protected]')->first();

You can even add multiple fields:

return $this->users->whereNameAndAge('Foo', 100)->first();

The above can result in more readable code as opposed to chaining where clauses. It depends on the query though and preference.