Search code examples
phpmysqlsqllaravel-4

`date_sub` not working in SQL via laravel


I'm having an issue with the following laravel code not returning any rows when executed in Laravel:

$entries = DB::table('chemlog')
        ->where('timestamp', '>=','DATE_SUB(NOW(), INTERVAL 1 DAY')
        ->orderBy('timestamp','desc')
        ->get();

When I execute the following on the MySQL console, it works fine:

SELECT * FROM chemlog WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)

What is the difference between what Laravel is assembling and what I wrote on the console?

I'm using:

PHP 5.5, MySQL 5.6, Laravel 4


Solution

  • Use raw statement:

    ->where('timestamp', '>=', DB::raw('DATE_SUB(NOW(), INTERVAL 1 DAY)'))
    

    The difference is that this is a parametrized query, so it's basically treating it as a string