Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?