I'm trying to create a report page that shows reports from a specific date to a specific date. Here's my current code:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();
What this does in plain SQL is select * from table where reservation_from = $now
.
I have this query here but I don't know how to convert it to eloquent query.
SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to
How can I convert the code above to eloquent query? Thank you in advance.
The whereBetween
method verifies that a column's value is between
two values.
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
In some cases you need to add date range dynamically. Based on @Anovative's comment you can do this:
Reservation::all()->filter(function($item) {
if (Carbon::now->between($item->from, $item->to) {
return $item;
}
});
If you would like to add more condition then you can use orWhereBetween
. If you would like to exclude a date interval then you can use whereNotBetween
.
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
Other useful where clauses: whereIn
, whereNotIn
, whereNull
, whereNotNull
, whereDate
, whereMonth
, whereDay
, whereYear
, whereTime
, whereColumn
, whereExists
, whereRaw
.