Eloquent whereNotBetween Query Laravel 12 With Example

The `whereNotBetween` method in Laravel 12 Eloquent allows you to filter records where a column’s value does not fall between two specified values. Here’s how to use it with examples:

Syntax

Model::whereNotBetween('column_name', [$minValue, $maxValue])->get();

Examples

Example 1: Excluding Records Within a Date Range

<?php
// Get users who were NOT registered between Jan 1 and Dec 31, 2023
$users = User::whereNotBetween('created_at', [
'2023-01-01 00:00:00',
'2023-12-31 23:59:59'
])->get();
?>

Example 2: Excluding Products Within a Price Range

<?php
// Get products priced outside $10 to $100 range
$products = Product::whereNotBetween('price', [10, 100])
->orderBy('price')
->get();
?>

Example 3: Combining with Other Conditions

<?php
// Get active orders that were NOT placed between two dates
$orders = Order::where('status', 'active')
->whereNotBetween('order_date', [
'2024-01-01',
'2024-03-31'
])
->get();
?>

Example 4: Using with Relationships

<?php
// Get authors whose books were NOT published between 2010-2020
$authors = Author::whereHas('books', function($query) {
$query->whereNotBetween('published_year', [2010, 2020]);
})
->get();
?>

Dynamic WhereNotBetween

<?php
// Using variables for dynamic ranges
$minAge = 18;
$maxAge = 30;

$users = User::whereNotBetween('age', [$minAge, $maxAge])
->get();
?>

Important Notes:

1. The `whereNotBetween` method is inclusive of the boundary values
2. For date ranges, make sure to format dates properly
3. You can chain this with other query builder methods
4. Works with all supported Laravel database systems

Would you like me to show you how to use the `whereBetween` method (the opposite of this) as well?