Search code examples
phpsqlmysqloracle-databaseeloquent

How can I write a query with searching of full name?


I have a problem with the query which will search users by full name.

But when I typed

$user = Polzovatel::select()
    ->where(DB::raw("CONCAT(fam, ' ',imya)"), 'like', '%'. $request->input('polnoe_imya').'%')
    ->orWhere(DB::raw("CONCAT(fam, ' ',imya)"), 'like', '%'. $request->input('fullName').'%')
    ->get(); 

that return data of user only when request is equivalent to 'Tom Walke' or 'Walker To' but when my search request will be like 'To Wal' it just return empty array. So what can I do with this problem? Name and surname are in different column. But query with concatenate it is not quite correct


Solution

  • Put % around each word in the name, not just the whole name. So if the inpupt is To Wai, your pattern will be %To% %Wai%.

    $pattern = implode(' ', 
        array_map(function($word) { return "%$word%"; },
                  explode(' ', $request->input('fullName'))));
    $user = UserData::select()
        ->where(DB::raw("CONCAT(surname, ' ',name)"), 'like', $pattern)
        ->orWhere(DB::raw("CONCAT(name, ' ',surname)"), 'like', $pattern)
        ->get();