Retrieving Records Based on a Date Range Using Laravel
To retrieve records that fall within a specified date range, Laravel's Eloquent ORM provides the whereBetween method. This method allows you to specify a column name and an array of two dates, representing the start and end points of the desired range.
$from = date('2018-01-01'); $to = date('2018-05-02'); Reservation::whereBetween('reservation_from', [$from, $to]) ->get();
This query will retrieve all reservations where the reservation_from column value falls between January 1st, 2018 and May 2nd, 2018.
Dynamic Range Parameters
You can also dynamically define the start and end dates of the range using Carbon's between method:
Reservation::all() ->filter(function($item) { if (Carbon::now()->between($item->from, $item->to)) { return $item; } });
Additional Queries
Example:
Reservation::whereBetween('reservation_from', [$from1, $to1]) ->orWhereBetween('reservation_to', [$from2, $to2]) ->whereNotBetween('reservation_to', [$from3, $to3]) ->get();
Other Where Clauses
For further flexibility, Laravel offers additional WHERE clauses, including:
The above is the detailed content of How to Retrieve Records Within a Specific Date Range Using Laravel's Eloquent ORM?. For more information, please follow other related articles on the PHP Chinese website!