Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ryan_angelo's avatar

How to search by full name if first name and last name is in different columns?

Hi guys,

I am open for any ideas or solutions, I wanted to search data from the database by full name but first name and last name is in different columns inside the table.

For example i search Ryan Angelo,

In database:

firstname - Ryan

lastname - Angelo

Thanks!

0 likes
5 replies
Jaytee's avatar

User model:

public function getFullName()
{
    return "{$this->first_name} {$this->surname}";
}
tylernathanreed's avatar
Level 14

For multi-column search, I typically do something like this:

function scopeWithName($query, $name)
{
    // Split each Name by Spaces
    $names = explode(" ", $name);

    // Search each Name Field for any specified Name
    return User::where(function($query) use ($names) {
        $query->whereIn('first_name', $names);
        $query->orWhere(function($query) use ($names) {
            $query->whereIn('last_name', $names);
        });
    });
}

Then you can just call $user->withName($name)->get() or User::withName($name)->get().

Note: If you support spaces in your name fields, this will not work. You'll probably want to convert this to some sort of Regex. However, the structure of the solution I've given still applies.

Another Note: This solution does not consider name ordering. The query "Angelo Ryan" will find any Users named "Ryan Angelo".

4 likes
falgunatara's avatar

hii, can you please explain me if i have to set ordering as lastname firstname or firstname lastname both ways to search for a user then how I can do that using typeahead.js autocomplete search plugin in Laravel ?

1 like

Please or to participate in this conversation.