Laravel Eloquent: How to Use the BETWEEN Operator

Working with dates, prices, ranges, or intervals in your Laravel applications? The BETWEEN operator in Laravel Eloquent is a simple yet powerful tool that helps filter records within a given range. Whether you’re building an e-commerce app that filters products by price or analyzing user activity between two dates, between comes in handy.

In this comprehensive guide, we’ll explore:

  • What BETWEEN is and how it works
  • How to use whereBetween, orWhereBetween, whereNotBetween, etc.
  • Common real-world use cases
  • Important precautions
  • Pros and cons
  • Compatibility with Laravel versions
  • Performance tips and best practices

What is the BETWEEN Operator?

In SQL, BETWEEN is used to filter records between a start and end value, inclusive of both.
SELECT * FROM orders WHERE total BETWEEN 100 AND 500;

In Laravel, the same logic is used via Eloquent’s whereBetween() method.

Syntax of whereBetween in Laravel

Model::whereBetween(‘column_name’, [$start, $end])->get();

Example:

$users = User::whereBetween(‘age’, [18, 30])->get();

Returns all users where age is between 18 and 30, including both ends.

Whatever text you put inside must match a name from the official icon list.

Real-World Examples

1. Filter Products by Price

$products = Product::whereBetween(‘price’, [100, 500])->get();

2. Fetch Orders in a Date Range

Copy to clipboard
$orders = Order::whereBetween('created_at', [
'2024-01-01',
'2024-12-31'
])->get();

3. Logs for the Last 7 Days (using Carbon)

Copy to clipboard
use Carbon\Carbon;
$logs = ActivityLog::whereBetween('created_at', [
    Carbon::now()->subDays(7),
    Carbon::now()
])->get();

Additional Variants of between

orWhereBetween

Copy to clipboard
$users = User::whereBetween('age', [18, 25])
             ->orWhereBetween('age', [40, 50])
             ->get();

whereNotBetween

Copy to clipboard
$users = User::whereNotBetween('age', [20, 30])->get();

orWhereNotBetween

Copy to clipboard
$users = User::whereNotBetween('salary', [3000, 5000])
             ->orWhereNotBetween('age', [25, 40])
             ->get();

Precautions While Using whereBetween

Here are some important things developers should keep in mind:

1. Validate the Range

Ensure that the lower value is less than or equal to the upper value, especially with dynamic user input.

if ($min > $max) {
throw new InvalidArgumentException(“Minimum cannot be greater than maximum.”);
}

2. Correct Data Types

When dealing with:

  • Dates: Use Carbon for accurate formatting.
  • Decimals/floats: Ensure values are not unintentionally rounded.
  • Times: Use whereTime() if filtering by time only.

3. Avoid Using on Unindexed Columns

Filtering large datasets with whereBetween on non-indexed columns (e.g., text, json) will lead to slow queries.

4. Timezones and Dates

If you’re storing timestamps in UTC, but user input is in local time, convert inputs properly to avoid mismatches.

$start = Carbon::parse($request->start)->timezone(‘UTC’);

Laravel Version Compatibility

whereBetween, whereNotBetween, orWhereBetween, and orWhereNotBetween have been supported in Laravel since version 4.x, and are fully functional in all versions up to Laravel 12 (as of 2025).

This blog is 100% compatible with all Laravel versions (Laravel 5.x, 6.x LTS, 7, 8, 9, 10, 11, and 12).

Performance Tips

  • Use indexed columns to benefit from SQL range scans.
  • Don’t use SQL functions like DATE(column) inside a whereBetween. They negate indexes.
  • Consider indexing created_at, price, or other commonly filtered fields.

Pros and Cons of BETWEEN Operator

Pros Cons
Simple and readable syntax Limited to inclusive ranges only
Efficient on indexed numeric/date columns Can’t use for partial-matching text ranges (like LIKE)
Works with both numbers and timestamps Can cause performance issues on large, unindexed tables
Reduces need for multiple >= and <= conditions Doesn’t support “open-ended” ranges without manual logic (Only one side, either start or end value)
Clean when combined with scopes or query chains Can be tricky when timezone offsets are not considered properly

Best Practices

  • Use Carbon for all date manipulations.
  • Validate user inputs to prevent logic bugs or errors.
  • Index frequently queried fields for better performance.
  • Encapsulate reusable logic into local scopes:
Copy to clipboard
// In the Product model
public function scopePriceRange($query, $min, $max)
{
    return $query->whereBetween('price', [$min, $max]);
}
// Usage
$products = Product::priceRange(100, 500)->get();

Conclusion

The BETWEEN operator is a simple yet highly effective tool in Laravel Eloquent for filtering ranges of data, be it age, price, timestamps, or anything numerical.

When used wisely, especially with precautions around validation, indexing, and data types, it can significantly enhance the clarity and performance of your queries.

Need Help With Laravel Development?

Work with our skilled Laravel developers to accelerate your project and boost its performance.

Support On Demand!