Laravel Eloquent: Using WHERE NOT IN

Published on
2 mins read
––– views

Laravel Eloquent: Using WHERE NOT IN

In Laravel Eloquent, the "WHERE NOT IN" clause is used to exclude specific values from a query. Here's how you can implement this:

1. Using the whereNotIn Method

The whereNotIn method allows you to specify a column and an array of values that should be excluded from the query.

$excludedUserIds = [1, 2, 3];

$users = User::whereNotIn('id', $excludedUserIds)->get();

2. Using the where Method with not in

You can achieve the same result using the where method with the not in condition.

$excludedUserIds = [1, 2, 3];

$users = User::whereNotIn('id', $excludedUserIds)->get();

3. Dynamic "WHERE NOT IN" Conditions

If you need to dynamically generate the "WHERE NOT IN" conditions based on user input or other factors, you can use variables.

$excludedUserIds = [1, 2, 3];

$users = User::where(function ($query) use ($excludedUserIds) {
    $query->whereNotIn('id', $excludedUserIds);
})->get();

4. Using Eloquent Relationships

You can also apply "WHERE NOT IN" conditions when working with Eloquent relationships.

$excludedRoleIds = [4, 5, 6];

$users = User::whereHas('roles', function ($query) use ($excludedRoleIds) {
    $query->whereNotIn('id', $excludedRoleIds);
})->get();

Note

  • Adjust the column names and conditions based on your specific use case.

  • The "WHERE NOT IN" clause is useful when you want to exclude specific values from the result set.

By incorporating these techniques, you can effectively use "WHERE NOT IN" in Laravel Eloquent for more precise queries.