1

I'm having trouble getting access to a variable that is available outside of my method call. (Using Laravel) An example:

    print "Here is my name: $name\n";

    return Foo::find(1)->whereHas('bar', function($q) {
        global $name;
        print "Unfortunately this name is blank: " . $name;
        $q->where('name', 'like', '%' . $name . '%');
    })->first();

$name inside the whereHas function is always blank. If I don't declare it as $global, then I get a warning that $name doesn't exist at all. How do I get access to it?

1 Answer 1

2

You can send references to anonymous functions (i.e., Closures) with the use keyword:

$name = 'foo';
return Foo::find(1)->whereHas('bar', function($q) use ($name) {
    print "Here name should be : " . $name; // foo
    $q->where('name', 'like', '%' . $name . '%');
})->first();

btw i have not tested this, but its supposed to work

Sign up to request clarification or add additional context in comments.

1 Comment

Nice shot sir! I had no idea about the use() keyword. Worked like a charm. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.