Miskate Erorr Miskate Erorr - 6 months ago 15
SQL Question

How to apply Mysql AND/OR clause in Laravel

I am trying to make a MySQL query inside Laravel.

> "select * from users u where (name like
> '%".$request->search_string."%' or email like
> '%".$request->search_string."%') and (user_type=2)";


I tried the code below

public function searchUsers(Request $request){
$query = DB::table('users as u');
$query->where('u.user_type',2);
$query->where(function($query,$request){
$query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
$query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
});
$result['all_users'] = $query->get();
return Response::json($result);
}


But I am getting the following error


Missing argument 2 for
App\Http\Controllers\PatientController::App\Http\Controllers{closure}()

Ali Ali
Answer

You have syntax error in where clause. See this:

public function searchUsers(Request $request){
        $query = DB::table('users as u');
        $query->where('u.user_type',2);
        $query->where(function($query)use($request){ // Here  is the change
                    //  ^^ Pass only one parameter to closure function and pass `$request` in `use` function
            $query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
            $query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
        });
        $result['all_users'] = $query->get();
    return Response::json($result);
}
Comments