Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luisrenelopez's avatar

PHP Notice: Undefined variable: num in Psy Shell code on line 4

Hi

For some reason php can not read the variable $num, I get this error "PHP Notice: Undefined variable: num in Psy Shell code on line 4" when running this code:

App\Chat::where(function ($query) { $query->where('from', 1 )->where('to', $num ); })->orWhere( function ($query) { $query->where('from', $num )->where('to',1); })->where( 'from', $num )->get()

I had previously defined $num = 1;

the code works only if i put directly the number 1 in the code instead of the variable $num

So why php can not read the $num variable?

0 likes
2 replies
MichalOravec's avatar
Level 75

You have to use use ($num) when you pass data to the closure.

App\Chat::where(function ($query) use ($num) { 
    $query->where('from', 1)->where('to', $num); 
})->orWhere(function ($query) use ($num) { 
    $query->where('from', $num)->where('to', 1); 
})->where('from', $num)->get();
1 like

Please or to participate in this conversation.