laravel search multiple words separated by space

前端 未结 7 1957
鱼传尺愫
鱼传尺愫 2020-12-29 08:57

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 o

7条回答
  •  情歌与酒
    2020-12-29 09:48

    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);
    array(
      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';
    
    // split on 1+ whitespace & ignore empty (eg. trailing space)
    $searchValues = preg_split('/\s+/', $string, -1, PREG_SPLIT_NO_EMPTY); 
    
    $users = User::where(function ($q) use ($searchValues) {
      foreach ($searchValues as $value) {
        $q->orWhere('name', 'like', "%{$value}%");
      }
    })->get();
    

    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.

提交回复
热议问题