Laravel 5 query builder and NOW() for date comparison
13,088
Eloquent Query builder doesn't accept those specific SQL functions but as it's done within your PHP you can easily use the great Carbon Class : http://carbon.nesbot.com/docs/ :
use Carbon\Carbon;
And then,
$job = $jobs->where('closing_at', '>=', Carbon::now())
->orderBy($sorter[0], $sorter[1])->paginate(24);
That should do the trick.
There is also a whereDate() eloquent method : https://laravel.com/docs/5.3/queries#where-clauses
Related videos on Youtube
Author by
TH1981
Updated on June 04, 2022Comments
-
TH1981 8 months
My database (MySQL) has a timestamp field for
created_at
.I have two entries, with the timestamps as follows:
- 2017-12-12 18:25:00
- 2016-10-02 18:00:00
Today is 2016-10-19 (for future reference). If I use the following query, I get no results:
$job = $jobs->where('closing_at', '>=', 'NOW()') ->orderBy($sorter[0], $sorter[1])->paginate(24);
If I hardcode the date, I get the correct results, just the one future date:
$job = $jobs->where('closing_at', '>=', "2016-10-19 00:00:00") ->orderBy($sorter[0], $sorter[1])->paginate(24);
I'm assuming my error is in the use of
NOW()
with the Eloquent query builder but I can't figure out the correct way to use this is.-
Lars Mertens about 6 yearsInstead of NOW(), i guess you need \Carbon::now()
-
xAocDB::raw or whereRaw should help you laravel.com/docs/5.3/queries#raw-expressions
-
TH1981 about 6 yearsThat does it. Doesn't make sense to me that Eloquent doesn't accept the basic SQL function, but it works. thanks
-
2Fwebd about 6 yearsThat'd work on the DB:: object : laravel.com/docs/5.3/queries but not on a modal called by eloquent because it's "managed by PHP" in the first place.