Eloquent search in two columns using like

2019-07-23 17:21发布

Hi guys can somebody help me

I need to search for users in a table from an text input

i did it if we search just by the name or by the last name but cant do it if we write both the name and the last name in the text input

this is the code when we write just the name or the last name:

$data = User::where('name', 'LIKE', '%'. $search .'%')
                 ->orWhere('firstname', 'LIKE', '%'. $search .'%')
                 ->get();

i think its something like this but it doesn't work :D

first i did split the text given from the input here is the code

$words = explode(' ', $search);
    $firstword = $words[0];
    $lastword = $words[1];


$data = User::where('name', 'LIKE', '%'. $firstword .'%')
                       ->where('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();

3条回答
该账号已被封号
2楼-- · 2019-07-23 17:39

You could do something like this to search for all the words against both the first name and last name columns:

// Get the search terms and define the columns we're looking at
$terms = explode(' ', $search);
$columns = ['firstname', 'lastname'];

// Start with an initial null query. I'm pretty sure Laravel expects a where before an orWhere, so this is an alright way to make that check.
$query = null;

// For each of the search terms
foreach ($terms as $term) {
    // For each column
    foreach ($columns as $column) {
        // If we have not yet started a query, start one now by applying a where to the User model. If we have started a query i.e. $query is not null, then use an orWhere
        if (is_null($query)) {
            $query = User::where($column, 'LIKE', '%' . $term . '%');
        } else {
            $query->orWhere($column, 'LIKE', '%' . $term . '%');
        }
    }
}

// Finally, get the results
$results = $query->get();
查看更多
Explosion°爆炸
3楼-- · 2019-07-23 17:43

your problem was this (orWhere instead where):

$data = User::orWhere('name', 'LIKE', '%'. $firstword .'%')
                       ->orWhere('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();
查看更多
成全新的幸福
4楼-- · 2019-07-23 17:47

) you can do something like this

$posts = Post::where('COLUMN_ONE','SEARCH STRING')->orWhere('COLUMN_TWO','LIKE','%'.$search)->paginate(2);

hope this helps

查看更多
登录 后发表回答