Passing data to a closure in Laravel 4

PhpLaravelLaravel 4

Php Problem Overview


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.com', 'Sender');
});

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

Any ideas ?

Php Solutions


Solution 1 - Php

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.com', 'Sender');
});

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenjamin GonzalezView Question on Stackoverflow
Solution 1 - PhpBlessingView Answer on Stackoverflow