Why do Where and orWhere have conflicts?


I have made a search with eloquent laravel, but I had a problem at the moment of having 2 where and% orWhere , since in my database we work for state [0, 1] to see if a record has been low.

But when searching for a user, the following occurs:

$users = User::where('code', 'LIKE', '%'.$request->search.'%')
                  ->orWhere('name', 'LIKE', '%'.$request->search.'%')
                  ->where('state', 1)

I put the where at the end to only show me the users who have not been unsubscribed, but they still show me when they search.

return $users;

    "id": 1,
    "code": "USR-001",
    "name": "Jhon Smith",
    "state": 0
    "id": 2,
    "code": "USR-002",
    "name": "Carlos Smith",
    "state": 1
asked by Carlos Mendez 05.10.2018 в 17:56

1 answer


What you have to use is a funcion to be able to control the where and the orWhere .

Try this:

$search = $request->search;
$users = User::where('state', 1)->where(function($query) use ($search){
                  $query->where('code', 'LIKE', '%'.$search.'%')
                  ->orWhere('name', 'LIKE', '%'.$search.'%');
answered by 05.10.2018 / 18:08