Coder Perfect

In Laravel 4, data is passed to a closure.

Problem

I’m trying to use Laravel 4’s Mail Class, however I can’t give 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');
});

I’m getting an error that the $team object isn’t available for some reason. I’m guessing it has something to do with the scale of the project.

Any ideas ?

Asked by Benjamin Gonzalez

Solution #1

The $team variable is not in the function’s scope if it was created outside of the function. Make use of the keyword use.

$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.

Answered by Blessing

Post is based on https://stackoverflow.com/questions/14482102/passing-data-to-a-closure-in-laravel-4