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 All

Laravel CORS Example: How to Enable CORS in Laravel?


In this tutorial, i will teach you how to easily enable CORS (Cross-Origin Resource Sharing) in Laravel and work with it.

Laravel 9 Generate Sitemap XML File Tutorial


Learn how to generate a sitemap.xml file in Laravel 9 with this step-by-step tutorial. Improve your website's SEO and enhance user experience.

Laravel Eloquent Query - Laravel whereKey method


We'll look at the whereKey method in Laravel Eloquent in this post. whereKey is an extremely easy-to-use tool with a lot of potential.

Laravel 9 Socialite Login with LinkedIn Tutorial Example


How to use the Laravel socialite, Livewire, and Jetstream libraries to create a LinkedIn login system from scratch in Laravel

Laravel 9 Install Vue Auth Tutorial with Example


In this article, I'll demonstrate how to use the Laravel UI and Vue Auth scaffolding to create login, register, logout, forget password, profile, and...