How to Search First Name and Last Name in Laravel Query?

By Hardik Savani April 16, 2024 Category : Laravel

Hi,

In this tutorial we will go over the demonstration of how to search first name and last name in laravel. In this article, we will implement a laravel get user full name search. We will use laravel search by full name. this example will help you search first name and last name in laravel. you will do the following things for laravel first name and last name where condition.

Mostly we take two columns first name and last name for full name. but when you need to add one input box and search full name then we have to think about it because we taken two separate columns. But not worry about it, i will give you very simple example how to search first name and last name in laravel query builder using orWhere() and DB.

Here, i will give you three examples that you can use with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 version.

Example 1:

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\User;

use DB;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$search = "Hardik Sa";

$users = User::select("id", "first_name", "last_name")

->orWhere(DB::raw("concat(first_name, ' ', last_name)"), 'LIKE', "%".$search."%")

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 127

[first_name] => Hardik

[last_name] => Savani

)

)

Example 2:

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\User;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$search = "Hardik Sa";

$users = User::select("id", "first_name", "last_name")

->whereRaw("concat(first_name, ' ', last_name) like '%" .$search. "%' ")

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 127

[first_name] => Hardik

[last_name] => Savani

)

)

Example 3:

Controller Code:

<?php

namespace App\Http\Controllers;

use App\Models\User;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$search = "Sa";

$users = User::select("id", "first_name", "last_name")

->where(function ($q) use ($search) {

$q->orWhere('first_name', 'like', "%{$search}%")

->orWhere('last_name', 'like', "%{$search}%");

})

->get();

dd($users);

}

}

Output:

Array

(

[0] => Array

(

[id] => 127

[first_name] => Hardik

[last_name] => Savani

)

)

i hope it can help you...

Tags :
Shares