What the best way to use now() with Eloquent? I mean, is there a native Eloquent function to return today's date? I'm using Slim framework and for this query, the only solution that I found is:
$now = date('Y/m/d H:i:s', time());
$articles = Article::where('created_at', '<', $now)
->orderBy('created_at', 'DESC')
->limit(10)
->get();
It's a bit messy, isn't it? I could use Carbon but it would make an extra dependency...
Thanks
You have two options here: either use DB::raw
method to make where
method process the given expression as is:
$articles = Article::where(DB::raw('created_at < NOW()'))
->orderBy('created_at', 'DESC')
->limit(10)
->get();
... or use whereRaw
method:
$articles = Article::whereRaw('created_at < NOW()')
->orderBy('created_at', 'DESC')
->limit(10)
->get();
As a sidenote, Eloquent has several helper methods for datetime-related processing - whereDate
, whereMonth
, whereDay
, whereYear
and whereTime
. I'm really not sure those can be used in this specific case, but they might turn helpful elsewhere.