Query Value Ranges with whereValueBetween()
Sometimes you have a value and need to find database records where that value falls between two columns.
For example, a product may have:
min_price max_price
and you want to find products that support a specific price.
The Old Way
You could use whereRaw():
$price = 100;
$products = Product::whereRaw(
'? BETWEEN min_price AND max_price',
[$price]
)->get();
But Laravel provides a cleaner method.
Use whereValueBetween()
$price = 100;
$products = Product::whereValueBetween(
$price,
['min_price', 'max_price']
)->get();
Laravel checks whether the value falls between the two specified columns.
Conceptually:
min_price <= 100 <= max_price
Real-World Example
Imagine a shipping system where each rule has a minimum and maximum order value:
min_order_value max_order_value shipping_cost
You can find the matching shipping rule:
$orderTotal = 750;
$rule = ShippingRule::whereValueBetween(
$orderTotal,
['min_order_value', 'max_order_value']
)->first();
This keeps the query readable and avoids manually writing SQL.
Find Values Outside the Range
Laravel also provides whereValueNotBetween():
$products = Product::whereValueNotBetween(
$price,
['min_price', 'max_price']
)->get();
This finds records where the value is outside the specified range.