2

I have an array of emails I need to send a message to in Laravel 4.2. This array is

$email_arr = ["me@yahoo.com","friend@gmail.com"]

Now my logic is to simply iterate through the email array and send a message to each one, like so:

foreach($email_arr as $email){
            Mail::send('emails.invite', array('pool_code' => 'test'), function($message) {
                $message->to($email)->subject('Join my capture pool!');
            });
        }

However, I get an error pointing to $message->to($email)->subject('Join my capture pool!'); which says Undefined variable: email.

I find this strange as the variable clearly exists, and if I echo $email within the loop it prints out each email correctly.

So what's happening here?

0

1 Answer 1

12

You have anonymous function (a.k.a closure), which dosen't have $email in its scope.

Closures (anonymous functions) may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

You have to add use to this function.

foreach($email_arr as $email){
    Mail::send('emails.invite', array('pool_code' => 'test'), function($message) use($email) {
        $message->to($email)->subject('Join my capture pool!');
    });
}
1
  • Yup, that does it. Thanks. Will accept the answer in 10 minutes. Oct 9, 2015 at 11:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.