• iconJakarta, Indonesia
  • iconlaratech.channel@gmail.com

+62081290348080

icon

Need Help?

+62081290348080

Laravel Eloquent whereRaw Method | How to use Laravel Eloquent whereRaw() Method

Laravel Eloquent whereRaw Method | How to use Laravel Eloquent  whereRaw() Method

Laravel Eloquent whereRaw Method | How to use Laravel Eloquent whereRaw() Method

Hello Everyone, In this article, you will learn how to use the whereRaw() method in Laravel Eloquent.

 

Laravel provides a new eloquent function whereRaw(), by using the whereRaw() method you can easily use the MySQL function and make it easily where condition. So, let's see the below examples:

 

How to use it in your laravel project.

 

Example 1:

 

 public function index()
    {
        $users = User::query()
        ->whereRaw('YEAR(created_at) == ? AND MONTH(created_at) == ?', [date('Y'),date('m')])
        ->get();   

        dd($users);
  }

 

Example 2:

 

By using raw SQL Query you can determine the same result as the eloquent: below is the syntax:

 

"select * from `users` where YEAR(created_at) 
== ? AND MONTH(created_at) == ?"

 

By using raw Laravel Eloquent:

 

 public function index()
 {
    
  $users = User::query()
  ->whereRaw('YEAR(created_at) == ? AND MONTH(created_at) == ?',[date('Y'),date('m')])->get();

    dd($users);
 }

Thank you for reading this article, if you have anything that you wanted to ask leave your comment and we discuss it. I hope you understand a Laravel Eloquent whereRaw Method | How to use Laravel Eloquent whereRaw() Method by now.
{"id":1,"name":"Laratech","username":"admin","avatar":"users\\June2022\\WSYjSsq966HbiJIgJyhx.png"}

About the author:

Laratech is a fullstack developer based in Indonesia.
You can find more about him at Twitter

0 Comments

Leave a comment

Tags