Laravel Eloquent whereRaw Query Example

Laravel where raw query example, you will learn how to write where raw and where DB raw query in laravel.

You can use the laravel whereRaw eloquent method to building query in laravel apps. And also use laravel where raw with multiple conditions in eloquent queries.

Follow the below examples and learn how to write query using whereRaw in laravel:

Example 1: Laravel whereRaw Query using Model

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

When you dump the above given whereRaw query you will get the following SQL query:

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

Example 2: whereRaw Query using Query Builder

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

    dd($users);
}

When you dump the above given whereRaw query you will get the following SQL query:

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

Example 3: whereRaw with multiple conditions in Laravel

Here’s an example of using whereRaw with multiple conditions in Laravel:

$minAge = 25;
$maxVotes = 100;

$users = DB::table('users')
    ->whereRaw('age > ? and votes <= ?', [$minAge, $maxVotes])
    ->get();

Conclusion

That’s it; you have learned how to use whereRaw with multiple conditions in laravel apps.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *