Laravel Eloquent whereRaw Condition Example

By Hardik Savani April 16, 2024 Category : Laravel

Now, let's see post of laravel whereraw example. this example will help you laravel eloquent whereraw example. you will learn how to use whereraw in laravel. let’s discuss about whereraw concat in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 project.

Laravel provide new eloquent function whereRaw(), using whereRaw you can easily use mysql function and make it easily where condition. so here i will give you two example one concat function and another date_format function with whereRaw.

You can see bellow syntax on orWhere query in laravel:

whereRaw(SQL Condition, Array Value);

Example 1: Laravel whereRaw() with Concat()

SQL Query:

"select * from `users` where concat(first_name,' ',last_name) = ?"

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$search = "Hardik Savani";

$users = User::select("*")

->whereRaw("concat(first_name,' ',last_name) = ?", [$search])

->get();

dd($users);

}

}

Example 2: Laravel whereRaw() with DATE_FORMAT()

SQL Query:

"select * from `users` where DATE_FORMAT(created_at, '%d-%m-%Y') = ?"

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*")

->whereRaw("DATE_FORMAT(created_at, '%d-%m-%Y') = ?", [date('d-m-Y')])

->get();

dd($users);

}

}

I hope it can help you...

Shares