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('welcome@website.com', 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;
}
You missed the use
keyword. Change the code to :
foreach($recipients as $recipient) {
Mail::send('emails.shareListing', $data, function($m) use($recipient) {
$m
->from('share@asd.com', 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.
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) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.