PHP Laravel Variable Scope in functions

Hillcow

I have the following code in a Laravel controller, but the given parameter variable $idea is undefined in the 'whereIn' function. How can I access $idea there? Thank you!

public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}
Moak

Use the use keyword! See Example #3 Inheriting variables from the parent scope on anonymous functions

public static function getIdea($idea = null) {
    if ($idea != "") {
        return DB::table('test')->select('foo')
            ->whereIn('bar', function($query) use ($idea)
              {
                  $query->select('foobar')
                        ->from('bar2')
                        ->where('foo2', '=', $idea)
                        ->get();
              })
            ->get();
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related