We will be taking an example to discuss whereraw concat in Laravel 6, Laravel 7, Laravel 8, and Laravel 9 projects.
Laravel provides a new eloquent function whereRaw(), using whereRaw and MySQL function. So we will be taking two examples one concat function and another date_format function with whereRaw.
You can see below syntax on or Where 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); } }