2

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}()
Marwelln
  • 28,492
  • 21
  • 93
  • 117
vlio20
  • 8,955
  • 18
  • 95
  • 180

1 Answers1

7

Your $tourId variable is not in the scope of your anonymous function. Have a look at the use 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.php

It should look something like the following:

$obj = $user->whereHas('tournaments', function($query) use($tourId)
    {
        var_dump($tourId); // Dumps OK
    })->get();
ChrisC
  • 2,461
  • 1
  • 16
  • 25