TH1981 TH1981 - 1 year ago 132
MySQL Question

Laravel 5 query builder and NOW() for date comparison

My database (MySQL) has a timestamp field for


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
with the Eloquent query builder but I can't figure out the correct way to use this is.

Answer Source

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 : :

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 :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download