If you’re working on a Laravel project and will have to use a MySQL function in the where clause, you can always use DB::raw() and whereRaw() (). You can see how to utilize the MySQL function in the “where” clause in this example. In this example, I just want to compare with the year of the created at the column, not the entire date, so I use the MySQL function Year(), which returns only the year from the timestamp and compares it to the given value. Two examples of how to use SQL functions in the where clause are shown. Let’s have a look at both cases.
1. Example
$data = DB::table("items")->select("items.*")
->where(DB::raw("Year(items.created_at)"),'2022')
->orderBy('items.created_at')
->get();
2. Example
$data = DB::table("items")->select("items.*")
->whereRaw(DB::raw("Year(items.created_at) = '2022'"))
->orderBy('items.created_at')
->get();
I hope you will like the content and it will help you to learn Laravel Where Clause with MySQL Function Example
If you like this content, do share.