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.
Recommended Posts
View AllLaravel Multiple Where Condition Example
Laravel multiple where condition, Laravel multiple where not working, Laravel multiple where same column, Laravel 8 Eloquent multiple where condition...
Laravel 9 CKeditor Image Upload With Example
install ckeditor laravel 9, ckeditor image upload not working laravel 9, how to upload image in ckeditor in laravel 9, how to upload image using ckedi...
Laravel 9 CKeditor Image Upload With Example
Learn how to easily upload images in CKEditor using Laravel 9 with this step-by-step tutorial and example code. Improve your web development skills no...
Laravel 9 Send SMS Notification to Mobile Phone Tutorial
Learn how to use the Vonage (nexmo) package in a Laravel application to send an SMS notice to a mobile phone.
Laravel whereMonth and whereYear Example
laravel whereMonth and whereYear example, whereMonth, whereYear, where condition in laravel 8, date function in laravel 8, whereMonth and whereYear in...