Back to writing
Laravel1 min read

Dynamic Where Clauses in Laravel Eloquent

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', 'foo@bar.baz')->first();

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

return $this->users->whereEmail('foo@bar.baz')->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. 

Thanks for reading.

More from the notebook