2

When I do a foreach() loop, the current array element's value $recipient is not defined on the line ->to($recipient). Why is this?

PHP Code (throws error)

foreach($recipients as $recipient) {
    Mail::send('emails.invite', $data, function($m){
        $m
            ->from('[email protected]', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has invited you!');
    });
}

Error

Notice: Undefined variable: recipient

PHP Code (NO error)

foreach($recipients as $recipient) {
    echo $recipient;
}

2 Answers 2

3

You missed the use keyword. Change the code to :

foreach($recipients as $recipient) {
    Mail::send('emails.shareListing', $data, function($m) use($recipient) {
        $m
            ->from('[email protected]', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has shared a listing with you!');
    });
}

See this documentation - especially the third example. Quote:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header.

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

1 Comment

You are welcome! Had the problem once to. The PHP documentation is saying not much about this.
1

It's because you're inside the scope of the function.

Assuming you're using the PEAR package here, I don't understand why you're passing a function at all: http://pear.php.net/manual/en/package.mail.mail.send.php

If you meant to be doing this, you can use the use keyword to pass the variable into the function scope:

function($m) use($recipient) {

Comments

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.