How to query between two dates using Laravel and Eloquent? How to query between two dates using Laravel and Eloquent? php php

How to query between two dates using Laravel and Eloquent?


The whereBetween method verifies that a column's value is betweentwo 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.

Laravel docs about Where Clauses.


Another option if your field is datetime instead of date (although it works for both cases):

$fromDate = "2016-10-01";$toDate   = "2016-10-31";$reservations = Reservation::whereRaw(  "(reservation_from >= ? AND reservation_from <= ?)",   [     $fromDate." 00:00:00",      $toDate." 23:59:59"  ])->get();


If you want to check if current date exist in between two dates in db:=>here the query will get the application list if employe's application from and to date is exist in todays date.

$list=  (new LeaveApplication())            ->whereDate('from','<=', $today)            ->whereDate('to','>=', $today)            ->get();