Laravel / Eloquent and date comparison

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

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

This does not work. I read the documentation and it looks like you cannot pass MySQL Laravel functions. timestamp - field datetime. How can I compare these dates in Laravel 4?

+8
eloquent laravel
source share
5 answers

The answer that user1977808 gave you is not very good, because MySQL cannot use the index in the timestamp column, since it must calculate the output of the DATE_SUB function for each row. Avoid such queries; they must process the entire table every time!

How about something like this:

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

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

+9
source share

As an alternative,

You can use the Carbon API , which is associated with Laravel.

 ModelName::where( 'timestamp', '>=', Carbon::now() )->get(); 

Link: http://laravel.com/docs/5.1/eloquent-mutators

+3
source share
 return MainContact::where('timestamp', '>=', time() - (24*60*60))->get(); 
+2
source share

You can also execute a raw request using:

 $results = DB::query( 'query' ); 

You do not return the model object back to var results

0
source share

You can also use whereDate() , whereDay() , whereMonth() and whereYear() . In this case, whereDate() can be used as such, with convenient Carbon date functions:

return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();

0
source share

All Articles