Find data between two date in Laravel

To fetch data between to date we can use whereBetween in laravel. Most of the time use that for send email on a subscription notification or something else let's jump to the code. ๐Ÿ‘‡

$from = date('2018-01-01');
$to = date('2018-05-02');

Exam::whereBetween('exam_at', [$from, $to])->get();

In some cases you need to add date range dynamically.

Exam::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 .

Exam::whereBetween('exam_from', [$from1, $to1])
  ->orWhereBetween('exam_to', [$from2, $to2])
  ->whereNotBetween('exam_to', [$from3, $to3])
  ->get();

Other useful where clauses, whereInwhereNotInwhereNullwhereNotNullwhereDatewhereMonthwhereDaywhereYearwhereTimewhereColumn whereExistswhereRaw