Multiple where conditions with ‘AND’ & ‘OR’ operators in laravel



in my laravel controller i’m trying to perform the following query for the user search.

$data = User::orderBy('id','DESC')
            ->where('email','LIKE','%'.$request->search."%")
            ->orwhere('first_name','LIKE','%'.$request->search."%")
            ->orwhere('last_name','LIKE','%'.$request->search."%")
            ->WHERE('role_id','=','3')
            ->paginate(12);

            return view('admins.participants.results',compact('data'))

                ->with('i', ($request->input('page', 1) - 1) * 12 );

What I really want to perform is,

SELECT * FROM USERS WHERE role_id='3' AND email LIKE '%search_string%' OR first_name LIKE '%search_string%' OR last_name LIKE '%search_string%' ;

But the above laravel query outputs all the users without considering the `role_id=3

Answer

You can use where callback

  $data = User::orderBy('id','DESC')
        ->where('role_id',3)
        ->where(function($query)use($request){
            $query->where('email','LIKE','%'.$request->search."%");
            $query->orwhere('first_name','LIKE','%'.$request->search."%");
            $query->orwhere('last_name','LIKE','%'.$request->search."%");
        })->paginate(12);

also you can change

'%'.$request->search."%"

to

"%{$request->search}%"


Source: stackoverflow