[FIXED] passed variable in nested where query in laravel 9

Issue

I am trying to use variable to nested where() query in laravel 9 but i get an error that variable Undefined

my code:

public function edit($id)
{
    $category = Category::findOrFail($id);

    $parents = Category::
                where('status' , 'active')
                ->where('id' , '<>' , $id)
                ->where(function($query){
                    return $query
                    ->whereNull('parent_id')
                    ->orWhere('parent_id', '<>', $id);
                })->get();
}

the error:

Undefined variable $id

Solution

in this section of your code: ->where(function($query){ you need use keyword to pass value inside this inner function as below:

->where(function($query) use ($id) { .. };

the detail for this action is:

  1. The closure is a function assigned to a variable, so you can pass it around
  2. A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword:
  3. use allows you to access (use) the succeeding variables inside the closure.
  4. use is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying $id inside the closure has no external effect, unless it is a pointer like an object is.
  5. You can pass in variables as pointers like in case of &$id. This way, modifying the value of $total DOES HAVE an external effect, the original variable’s value changes.
  6. Variables defined inside the closure are not accessible from outside the closure either.
  7. Closures and functions have the same speed. Yes, you can use them all over your scripts.

for more info read this.

Answered By – Mustafa Poya

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published