0

I want to create a nested parameter grouping in my query where the value of one of my nested where is gotten from the form.

if($request->view != '') {
    $query->where(function ($query) {
    $query->where('type', $request->view)
            ->orWhere('type', 2);
    })->get();
}

Right now I'm getting Undefined variable: request. How do I get the value of $request->view in the function?

Bindas Samuel
  • 52
  • 1
  • 8

4 Answers4

2

You're not passing the $request variable into the anonymous function. Have a look at the PHP documentation.

In order to make your code work, you have to change it as follows:

if($request->view != '') {
    $query->where(function ($query) use($request) { // <-- without use, your 
      $query->where('type', $request->view)         //     anonymous function
            ->orWhere('type', 2);                   //     cannot access $request
    })->get();
}
IlGala
  • 3,331
  • 4
  • 35
  • 49
  • `($request->view != '')` could just be `(!$request->view)` – party-ring Oct 03 '19 at 15:32
  • well not really... He's checking the `view` variable to be a **non empty string** so `(!$request->view)` will give a totally different result... Anyway I've simply copied and paste is code... to make an edit it should be `($request->view !== '')` as explained [here](https://stackoverflow.com/questions/718986/checking-if-the-string-is-empty) – IlGala Oct 03 '19 at 15:57
1
if($request->view != '') {
    $query->where(function ($query) use ($request) {
    $query->where('type', $request->view)
            ->orWhere('type', 2);
    })->get();
}
1

Add it to scope with use

if($request->view != '') {
    $query->where(function ($query) use ($request) {
        $query->where('type', $request->view)
            ->orWhere('type', 2);
    })->get();
}
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
1

In your case not need use orWhere(). you can use whereIn()

if($request->view != '') {
    $query->whereIn('type', [$request->view, 2])
}
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55