The `whereBetween` method in Laravel 12 Eloquent allows you to query records where a column's value falls between two values. Here's how to use it effectively in Laravel 12:
Practical Examples
1. Filtering by Date Range
<?php
// Get orders between two dates
$orders = Order::whereBetween('created_at', [
'2024-01-01',
'2024-12-31'
])->get();
// Using Carbon for dynamic dates
use Carbon\Carbon;
$startDate = Carbon::now()->subMonth();
$endDate = Carbon::now();
$recentOrders = Order::whereBetween('created_at', [
$startDate,
$endDate
])->get();
?>
2. Filtering by Numeric Range
<?php
// Products with prices between 1000 and 5000
$products = Product::whereBetween('price', [1000, 5000])
->orderBy('price')
->get();
// Users with age between 18 and 30
$users = User::whereBetween('age', [18, 30])
->where('active', true)
->get();
?>
3. Combining with Other Conditions
<?php
$results = Booking::whereBetween('check_in_date', [$start, $end])
->where('status', 'confirmed')
->whereHas('room', function($query) {
$query->where('type', 'deluxe');
})
->get();
?>
4. Using with Query Builder
<?php
// Using DB facade
$records = DB::table('transactions')
->whereBetween('amount', [500, 2000])
->get();
?>
5. Dynamic Where Between
<?php
// Dynamic range from request
$min = request('min_price', 0);
$max = request('max_price', 10000);
$products = Product::when($min && $max, function($query) use ($min, $max) {
$query->whereBetween('price', [$min, $max]);
})
->get();
?>
Alternative: whereNotBetween
<?php
// Records NOT between the range
$products = Product::whereNotBetween('price', [1000, 5000])->get();
?>
Performance Tips
1. For large tables, ensure the column used in `whereBetween` is indexed
2. When using with dates, consider timezone conversions if needed
3. For better readability with complex queries, use named scopes:
<?php
// In your model
public function scopePriceRange($query, $min, $max)
{
return $query->whereBetween('price', [$min, $max]);
}
// Usage
$products = Product::priceRange(1000, 5000)->get();
?>
The `whereBetween` method is particularly useful for filtering reports, analytics dashboards, and any scenario where you need to work with ranges of values.