In Laravel 11 Laravel 12, the `whereNotIn()` method is used to filter out specific values from a column. It is the opposite of `whereIn()` and is helpful when you want to exclude certain records from the query results.
1. Basic `whereNotIn()` Example
$users = User::whereNotIn('role', ['admin', 'editor'])->get();
Explanation:
– Retrieves all users except those with roles `admin` and `editor`.
– Works on arrays of values.
2. `whereNotIn()` with Multiple Conditions
$users = User::whereNotIn('role', ['admin', 'editor']) ->where('status', 'active') ->get();
Explanation:
Excludes `admin` and `editor` roles.
Only fetches users with `active` status.
3. Using `whereNotIn()` with Query Builder
use Illuminate\Support\Facades\DB; $products = DB::table('products') ->whereNotIn('category', ['electronics', 'furniture']) ->get();
Explanation:
Excludes products in the “electronics” and “furniture” categories.
4. `whereNotIn()` with Dynamic Data (Array from Request)
$excludedRoles = ['subscriber', 'guest']; $users = User::whereNotIn('role', $excludedRoles)->get();
Explanation:
– Uses a dynamic array for filtering.
– Useful when excluding roles dynamically from request input.
5. `whereNotIn()` with Pagination
$users = User::whereNotIn('role', ['admin', 'editor'])->paginate(10);
Explanation:
– Excludes `admin` and `editor` roles.
– Returns results paginated (10 per page).