Trying to attach ajax search by entity to sorting in one query. The entity contains the fields firstmane and lastname, for example. Searching for one field is not difficult, like this:

$users = User::where('firstname', 'LIKE', $request->firstname)->get(); 

But how best to organize a search on the basis of different fields of the entity in one line on the front end? For example, the string "Sergey Iva" returned the lines of Sergey Ivanov, Sergey Ivanchenko and so on.

There are ideas in the direction of regular expressions, but can there be more simple methods?

    2 answers 2

    If you need to search by firstname + lastname, then in the request combine them into one field and look for this field.

     SELECT CONCAT_WS(' ', firstname, lastname) as fullname FROM users where fullname like '%имя пользователя%' 

    If you need to search for several fields at the same time - look in the direction of full-text search, it is implemented quite simply in one query. Do not forget to put down the indexes in the table.

      It is possible so:

       protected function search(Request $request) { try { $data = User::where('first_name', 'like', '%' . $request->search . '%') ->orWhere('last_name', 'like', '%' . $request->search . '%') ->paginate(15); } catch (Exception $e) { if (App::environment('local')) { throw $e; } return responseJSON('DB ERROR', 'error'); } return view('home.index') ->with(['data' => $data]); }