A
A
Andrey Suha2020-03-02 11:54:31
Laravel
Andrey Suha, 2020-03-02 11:54:31

How to do a search on two fields?

There is a User model. It has two fields first_name and last_name. When I enter a search query like "Yves" then I can find a user let's say first_name Ivan and last_name Ivanov. But how to make a request if Ivan Ivanov is entered? So far, it only comes to mind to split the string into two elements and sort through all possible options. maybe there is some more elegant solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NubasLol, 2020-03-02
@andreysuha

foreach (explode(' ', $query) as $search) {
    $q->where(function($q) use ($search) {
        $q
            ->where('last_name', 'ilike', "%$search%")
            ->orWhere('first_name', 'ilike', "%$search%")

    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question