📜  eloquent where date between - PHP (1)

📅  最后修改于: 2023-12-03 15:30:37.169000             🧑  作者: Mango

Eloquent Where Clause with Date Between in PHP

When working with date ranges in your database, you might find yourself needing to select records that fall within a certain date range. Eloquent, the ORM provided by Laravel, makes this easy with the whereBetween method.

In this article, we'll walk through how to use the whereBetween method to select records between two dates.

The whereBetween Method

The whereBetween method allows you to select records where a column value falls within a specified range. The method takes two parameters: the name of the column you want to filter by, and an array containing the start and end dates of the range.

Here's an example of how to use whereBetween in Laravel's Eloquent ORM:

$users = DB::table('users')
                ->whereBetween('created_at', ['2021-01-01', '2021-12-31'])
                ->get();

In this example, we're selecting all records from the users table where the created_at column falls between January 1st, 2021 and December 31st, 2021.

You can also use whereBetween in a more object-oriented way by chaining it onto an Eloquent query:

$users = User::whereBetween('created_at', ['2021-01-01', '2021-12-31'])->get();

This code will select all User models where the created_at property falls within the specified range.

Conclusion

Using the whereBetween method in Eloquent allows you to easily select records that fall within a certain date range. By passing in an array of start and end dates, you can quickly filter your results and retrieve only the records you need.