How to use where clause with mysql function in Laravel 5?

By Hardik Savani | March 9, 2016 | | 1899 Viewer | Category : Laravel MySql


Share this post:

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. I add two example of how to use sql function in where cause. let's See both example.

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();