Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel check if date is between 2 dates.

I want to check if today's date is between to dates dat are stored in the database. Right now I do this with laravel eloquent:

 return Set::where('type', $type)
            ->where('active_from', '<=', date("Y-m-d"))
            ->where('active_until', '>=', date("Y-m-d"))
            ->first();

Is this correct?

like image 258
Jenssen Avatar asked Nov 09 '17 22:11

Jenssen


1 Answers

Assuming both active_from and active_until contains only dates it's correct, but if they contain dates with times you should probably use whereDate instead of where like so:

return Set::where('type', $type)
            ->whereDate('active_from', '<=', date("Y-m-d"))
            ->whereDate('active_until', '>=', date("Y-m-d"))
            ->first();

Also, looking at the code I'm pretty sure you should use operators the other way: active_from should be >= and active_until should be <=

like image 72
Marcin Nabiałek Avatar answered Oct 06 '22 17:10

Marcin Nabiałek