1

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
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36

2 Answers2

1
$parents = Category::
    where('status' , 'active')
    ->where('id' , '<>' , $id)
    ->where(function($query) use ($id) { <-- problem is here
        return $query
        ->whereNull('parent_id')
        ->orWhere('parent_id', '<>', $id);
    })->get();
Paul J.K
  • 603
  • 1
  • 4
  • 13
  • 1
    Please, add some explanation to help future readers to understand what was the mistake of the OP and why this code solve the issue. Thank you! – Syscall Aug 27 '22 at 10:52
  • @Syscall try to read this for more info: https://stackoverflow.com/questions/6320521/use-keyword-in-functions-php – Mustafa Poya Aug 28 '22 at 13:36
1

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.

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36