Discovering Laravel Latest Eloquent Methods: whereAll & whereAny

Eduar Bastidas • March 17, 2024

tips refactoring

In the ever-evolving world of web development, Laravel continues to introduce features that simplify and enhance the coding experience. The recent Laravel 10.47 update has brought us two innovative Eloquent methods that streamline database queries, especially when it comes to searching for data. Let’s dive into these methods and see how they can benefit your projects.

Traditionally, when implementing a search functionality in a Laravel application, you might find yourself writing lengthy queries to match various attributes. For instance, searching for orders by email or name would look something like this:

1// Traditional search query
2$orders->where('email', 'like', "%$search%")[^1^][1]
3 ->where('name', 'like', "%$search%");

WhereAll Method

With the introduction of the whereAll method, you can now condense this query into a more elegant and readable form:

1// Simplified with whereAll
2$orders->whereAll(['email', 'name'], 'like', "%$search%");[^1^][1]

This method generates a query that ensures all specified columns match the given criteria, making your code cleaner and more efficient.

WhereAny Method

On the other hand, the whereAny method offers flexibility by allowing any of the specified columns to match the criteria:

1// Flexible with whereAny
2$orders->whereAny(['email', 'name'], 'like', "%$search%");[^1^][1]

This results in a query that matches records if any of the columns meet the search term, perfect for broader search functionalities.

These methods not only make your codebase more maintainable but also enhance the readability and scalability of your applications. Embrace these new additions to the Laravel toolkit and watch your productivity soar!