Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel/Eloquent and comparing dates

I want to return all of the rows in my database table that are a day or less old. I'm using Laravel 4. This is what I tried:

$date = date('Y-m-d H:i:s');
return MainContact::where(DATEDIFF('timestamp', $date), '<=', 1)->get();

This doesn't work. I read the documentation and it doesn't seem like you can pass Laravel MySQL functions. timestamp is a datetime field. How can I compare these dates in Laravel 4?

like image 356
sehummel Avatar asked Jan 15 '13 20:01

sehummel


1 Answers

The answer that user1977808 gave you is not good because MySQL can't use an index on the timestamp column, since it has to compute an output of the DATE_SUB function for every row. Avoid such queries, they have to process the entire table every time!

How about something like this:

return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();

I put the >= in there because you said "a day or less old", so they must have timestamp that is later than yesterday.

like image 70
duality_ Avatar answered Oct 05 '22 06:10

duality_