Milind Daraniya

Laravel Eloquent whereBetween() Query Example

Published August 6th, 2023 10 min read

The whereBetween() method allows you to retrieve records from a database table that fall within a specified range of values for a particular column. This can be incredibly useful when you need to filter data based on a specific date or numeric range. Let's dive into an example:

$startDate = '2023-01-01';
$endDate = '2023-12-31';

$orders = Order::whereBetween('order_date', [$startDate, $endDate])->get();

📋 In the example above, we have a orders table with an order_date column. We want to retrieve all orders that fall within the range of January 1, 2023, to December 31, 2023.

🔎 We achieve this by calling the whereBetween() method on the Order model and passing the column name (order_date) as the first argument. The second argument is an array containing the start and end dates of the range.

🔥 The whereBetween() method will generate the appropriate SQL query to retrieve the desired records. In this case, it will be something like:

SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';

🎉 Finally, we call the get() method to execute the query and retrieve the results as a collection of Order models.

💡 Remember, the whereBetween() method is not limited to dates. You can use it with any column that holds a range of values such as prices, quantities, or any other numeric or date-based data.

Happy coding with Laravel Eloquent! 💻✨