DEV Community

srsagor
srsagor

Posted on

Laravel Where Clause with Mysql Function Example

When you are working on laravel projects and you need to use mysql function in where clause then you can easily use that using DB::raw() and whereRaw(). In this example you can show how to i use mysql function in where clause. In this example i want to compare with year of created_at field but not whole date, that's whay i use mysql function Year(), this function will return only year from timestamp and compare with given value.
Example 1:

$data = DB::table("items")->select("items.*")
->where(DB::raw("Year(items.created_at)"),'2016')
->orderBy('items.created_at')
->get();
Example 2:

$data = DB::table("items")->select("items.*")
->whereRaw(DB::raw("Year(items.created_at) = '2016'"))
->orderBy('items.created_at')
->get();

Top comments (0)