user4006175 user4006175 - 1 year ago 112
PHP Question

laravel search multiple words separated by space

I am new to laravel query builder, I want to search multiple words entered in an input field for example if I type "jhon doe" I want to get any column that contains jhon or doe

I have seen/tried solutions using php MySQL but can't able to adapt to query builder

//1. exploding the space between the keywords

//2. using foreach apend the query together

$query = "select * from users where";

$keywordRaw = "jhon doe";
$keywords = explode(' ', $keywordRaw );
foreach ($keywords as $keyword){
$query.= " first_name LIKE '%" + $keyword +"%' OR ";

how do I do this using query builder

this is what i have so far, what is the proper way of doing this,

$keywordRaw = "jhon doe";
//how do I explode this words and append them along with their appropriate query
$users = User::select('users.*')
->where('first_name', 'LIKE', '%'.$keywordRaw.'%')

please help, thanks in advance

Answer Source

This is how you do it with Query\Builder, but first some additional notes:

// user can provide double space by accident, or on purpose:
$string = 'john  doe';

// so with explode you get this:
explode(' ', $string);
  0 => 'john',
  1 => '',
  2 => 'doe'

// Now if you go with LIKE '%'.value.'%', you get this:
select * from table where name like '%john%' or name like '%%' or ...

That said, you obviously can't rely on explode because in the above case you would get all the rows.

So, this is what you should do:

$string = 'john  doe';

$searchValues = preg_split('/\s+/', $string); // split on 1+ whitespace

$users = User::where(function ($q) use ($searchValues) {
  foreach ($searchValues as $value) {
    $q->orWhere('name', 'like', "%{$value}%");

There is closure in the where because it is a good practice to wrap your or where clauses in parentheses. For example if your User model used SoftDeletingScope and you would not do what I suggested, your whole query would be messed up.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download