119

I'm trying to use the Mail Class in Laravel 4, and I'm not able to pass variables to the $m object.

the $team object contains data I grabbed from the DB with eloquent.

Mail::send('emails.report', $data, function($m)
{
   $m->to($team->senior->email, $team->senior->first_name. ' '. $team->senior->last_name );
   $m->cc($team->junior->email, $team->junior->first_name. ' '. $team->junior->last_name );
   $m->subject('Monthly Report');
   $m->from('info@website.example', 'Sender');
});

For some reason I get an error where $team object is not available. I suppose it has something to do with the scope.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Benjamin Gonzalez
  • 1,343
  • 2
  • 9
  • 11
  • Exact same scenario for me. The Mail::send issue lead to me searching about passing variables to closures and then back to this. Perhaps a sign something needs to be added to the laravel mailer docs on this? – ShaunUK Jan 12 '15 at 11:20

1 Answers1

251

If you instantiated the $team variable outside of the function, then it's not in the functions scope. Use the use keyword.

$team = Team::find($id);
Mail::send('emails.report', $data, function($m) use ($team)
{
   $m->to($team->senior->email, $team->senior->first_name . ' '. $team->senior->last_name );
   $m->cc($team->junior->email, $team->junior->first_name . ' '. $team->junior->last_name );
   $m->subject('Monthly Report');
   $m->from('info@website.example', 'Sender');
});

Note: The function being used is a PHP Closure (anonymous function) It is not exclusive to Laravel.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Blessing
  • 4,858
  • 1
  • 18
  • 13