โ ๏ธ This post links to an external website. โ ๏ธ
When building search functionality in Laravel, developers often write long chains of
orWhere()conditions. While effective, these queries can become repetitive and difficult to maintain. Laravel now offers a more elegant solution: whereAny().Traditional Approach: Verbose
orWhere()ChainsBefore
whereAny(), a typical multi-column search looked like this:User::where('name', 'LIKE', "%{$search}%")->orWhere('email', 'LIKE', "%{$search}%")->orWhere('phone', 'LIKE', "%{$search}%")->get();Modern Approach: Clean & Elegant whereAny()
Laravel simplifies this pattern dramatically:
User::whereAny(['name','email','phone'], 'LIKE', "%{$search}%")->get();Why
whereAny()Is a Game-Changer
- Cleaner and shorter code โ no repeated OR conditions.
- Easier to maintain โ simply add or remove fields in the array.
- Better readability โ the query's intention is instantly clear.
- More elegant and expressive โ fits Laravelโs philosophy perfectly.
Bonus Tip: Combine with Request Input
A practical example when building a search function:
$search = request('q');$users = User::whereAny(['name', 'email', 'phone'], 'LIKE', "%{$search}%")->get();Final Thoughts
The
whereAny()method may seem like a small improvement, but it greatly boosts readability and maintainability. If youโre still chaining multipleorWhere()calls, now is a great time to modernize your queries and take advantage of Laravelโs expressive syntax.
continue reading on laraveldailytips.com
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.