Comparing a value against multiple columns the easy way in Laravel
When working with Laravel, you might need to compare a value against multiple columns in the database. For instance, you might want to check if a value exists in one of the columns.
Typically, you would do something like this with query builder.
$users = User::query()
->where('email', 'LIKE', $email)
->orWhere('username', 'LIKE', $email)
->first();
This works, but in a recent release of Laravel, a new method called whereAll
and whereAny
were introduced. These methods allow you to compare a value against multiple columns more concisely.
Here’s how you can rewrite the previous example using whereAny
.
$users = User::whereAny(['email', 'username'], 'LIKE', $email)
->first();
This essentially adds a “where” clause to the query for multiple columns with “or” conditions between them. In this case, it’s checking if the email or username is like the given value.
You can also use whereAll
to compare a value against multiple columns with “and” conditions between them.
$users = User::whereAll(['email', 'username'], 'LIKE', $email)
->first();
This is a small change, but it can make your code more readable and concise. It’s a nice addition to the query builder and can be quite helpful when you need to compare a value against multiple columns in the database.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.