Home > Enterprise >  Date between two values - Lavarel SQL
Date between two values - Lavarel SQL

Time:10-09

I have a structure table like this: Start_date End_date

Now with today's date, I should go and get all the data including from Start_Date and End_Date, what can I do?

I tried with

select * from text WHERE Start_date BETWEEN '2021-10-10' AND '2021-10-08' OR End_date BETWEEN '2021-10-08' AND '2021-10-10'```

but to no avail ...

CodePudding user response:

The whereBetween method in Laravel will determine if an items value is between the given range.

$start = '2021-10-08';
$end = '2021-10-10';

Text::whereBetween('start_date', [$start, $end])
      ->whereBetween('end_date', [$start, $end])
      ->get();

CodePudding user response:

  1. if you just want to get data from start to end date you can use this eloquent Code
$start_date = "2020-10-20";
$end_date = "2021-10-20";
Text::where(function ($wh) use ($start_date, $end_date) {
   $wh->whereBetween('Start_date', [$start_date, $end_date])->orwhereBetween('End_date', [$start_date, $end_date]);
})->get();

here is a raw query from the above eloquent code

select * from `users` where (`Start_date` between '2020-10-20' and '2021-10-20' or `End_date` between '2020-10-20' and '2021-10-20')
  1. if you want to find data from start to end date including today's date you can you this eloquent Code
$start_date = "2020-10-20";
$end_date = "2021-10-20";
Text::where(function ($wh) use ($start_date, $end_date) {
   $today_date = date('Y-m-d');
   $wh->where(function ($or_where) use ($start_date, $end_date) {
      $or_where->whereBetween('Start_date', [$start_date, $end_date])
               ->orwhereBetween('End_date', [$start_date, $end_date]);
            })->orwhereRAW("('{$today_date}' between `Start_date` and `End_date`)");
})->get();

here is a raw query from the above eloquent code

select * from `text` where ((`Start_date` between '2020-10-20' and '2021-10-20' or `End_date` between '2020-10-20' and '2021-10-20') or ('2021-10-09' between `Start_date` and `End_date`))
  • Related