Reputation: 5568
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?
Upvotes: 12
Views: 45501
Reputation: 1248
You could also use whereDate()
, whereDay()
, whereMonth()
and whereYear()
. In this case, whereDate()
could be used as such, with Carbon's easy date functions:
return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();
Upvotes: 4
Reputation: 179
Alternatively,
You can use Carbon API that bundle with Laravel.
ModelName::where( 'timestamp', '>=', Carbon::now() )->get();
Reference: http://laravel.com/docs/5.1/eloquent-mutators
Upvotes: 9
Reputation: 3265
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
Upvotes: 2
Reputation: 18756
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.
Upvotes: 13
Reputation: 36
You can also do a raw query by using:
$results = DB::query( 'query' );
You only don't the the model object back in the results var
Upvotes: 0