NightMICU NightMICU - 8 months ago 36
PHP Question

Passing MySQL functions to Eloquent ORM query

I am trying to execute the following query in Eloquent ORM and cannot seem to execute the MySQL function -

$post = Post::where('slug', '=', $slug)->where('YEAR(created_at)', '=', $year)->first();

The exception I am getting is as follows -

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(created_at)' in 'where clause'

SQL: SELECT * FROM `posts` WHERE `slug` = ? AND `YEAR(created_at)` = ? LIMIT 1

Bindings: array (
0 => 'placeholder',
1 => 2013,

So, basically, it is encapsulating the
MySQL function as a column. Is there any way to do this without using a raw query?


You probably don't want to use the YEAR() function in your WHERE clause anyway. This would prevent you from using any index on the created_at column. I would suggest you use LIKE instead:

$post = Post::where('slug', '=', $slug)->where('created_at', 'LIKE', $year . '%')->first();

You can also just use raw SQL queries as well (using query() method) if you had need to utilize unsupported MySQL functions in your queries.