Hey fellow Laravel developers! Today, let's dive into two powerful methods available in Laravel's Eloquent ORM: whereIn and whereNotIn. These methods provide a convenient way to filter query results based on a list of values.
whereIn
allows you to filter your query results by matching values present in an array or a collection. It's perfect for scenarios where you want to fetch records that match any of the provided values. Here's an example:
$desiredRoles = ['admin', 'editor', 'contributor'];
$users = User::whereIn('role', $desiredRoles)->get();
// This will retrieve all users who have 'admin', 'editor', or 'contributor' roles
💡 In the above example, we use the whereIn
method on the User
model, specifying the column (role
) and the array of desired roles we want to match against. Laravel will automatically generate a query that fetches users with any of the roles in the provided array.
👉 On the other hand, whereNotIn
helps you exclude records that match any of the given values. It's handy when you want to retrieve results that do not fall within a specific set of values. Check out this example:
$undesiredStatuses = ['banned', 'inactive'];
$posts = Post::whereNotIn('status', $undesiredStatuses)->get();
// This will fetch all posts that are not 'banned' or 'inactive'
💡 In the above snippet, we apply the whereNotIn
method on the Post
model, specifying the column (status
) and the array of undesired statuses. Laravel will generate a query to retrieve posts whose status does not match any of the values in the provided array.