I have this function in php (laravel):
public static function isUserParticipatesInTournament($tourId, $userId)
{
var_dump($userId); //dumped
$user = User::find($userId);
if(!$user)
{
return null;
}
$obj = $user->whereHas('tournaments', function($query)
{
var_dump($tourId); //error
$query->where('id', '=', $tourId); //error
})->get();
return $obj;
}
The problem is that in the closure $obj = $user->whereHas('tournaments', function($query){...}
the $tourId
variable is undefined in it. I am getting this error:
Undefined variable: userId
.
Why this is happening? The variable is declared in the scope of the inner function. My only thought is that, that it is a callback function.
When I tried to execute this function : $obj = $user->whereHas('tournaments', function($query, $tourId){...}
then I am getting this exception:
Missing argument 2 for User::{closure}()
Your
$tourId
variable is not in the scope of your anonymous function. Have a look at theuse
keyword to see how you can add it to the scope. See example 3 on this page: http://www.php.net//manual/en/functions.anonymous.phpIt should look something like the following: