Hey Laravel developers! In Laravel 10, handling complex query conditions is made even more convenient. In this post, we'll explore how you can use multiple where clauses with AND-OR logic to build powerful queries. Let's dive in with a few examples!
Example 1: Suppose you want to fetch users who are either "admins" or "active contributors." You can achieve this using the following query:
$users = User::where('role', 'admin')
->orWhere('role', 'contributor')
->where('status', 'active')
->get();
💡 In the above example, we use the where
method to specify the initial condition where the role is "admin." We then chain an orWhere
method to add an alternative condition where the role is "contributor." Finally, we add another where
clause to further filter the results based on the "active" status.
👉 Example 2: Let's say you want to retrieve posts that have a title containing "Laravel" and belong to either category "Tutorials" or "News." Here's how you can do it:
$posts = Post::where('title', 'like', '%Laravel%')
->where(function ($query) {
$query->where('category', 'Tutorials')
->orWhere('category', 'News');
})
->get();
💡 In this example, we utilize the where
method with the like
operator to search for posts with "Laravel" in the title. Inside the second where
clause, we use a closure function to group the conditions and apply the OR logic. It filters posts that belong to either the "Tutorials" or "News" category.
👉 Example 3: Let's say you need to retrieve orders that were either placed in the year 2022 or have a total greater than $1000. Here's the query:
$orders = Order::whereYear('created_at', 2022)
->orWhere('total', '>', 1000)
->get();
In this example, we use the whereYear
method to filter orders created in the year 2022. We then chain an orWhere
clause to include orders with a total greater than $1000.
That's it for today's Laravel tip! 🔍 We hope these examples help you understand how to use multiple where
conditions with AND-OR logic in Laravel 10. Happy coding! 🎉