Passing parameters when writing a callback function in php (Laravel 5)

I'm programming in php using Laravel 5. I have this code.

    $newUser = $this->create($request->all());
    $newUser->save();

    $newAccount = new Account(['user_id' => $newUser->getAttribute('id')]);
    $newAccount->save();

    Mail::send('emails.welcome', ['username' => $newUser->name, 'active_token' => $newUser->active_token], function($message)
    {
        $message->to($newUser->email, $newUser->name)->subject('Welcome');
    });

The problem here is that I don't know how to pass the "newUser" variable within the callback function. It is not working because of the scope. So, how can I pass parameters when writing a callback function? in order to use them inside that scope?

Thank you

Upvotes: 3

Views: 7379

Answers (1)

Steve
Steve

Reputation: 20469

With php anonymous functions you can include variables from the parent scope with use($variable):

 Mail::send(
    'emails.welcome', 
    ['username' => $newUser->name, 'active_token' => $newUser->active_token],
    function($message) use($newUser)
    {
        $message->to($newUser->email, $newUser->name)->subject('Welcome');
    });

http://php.net/manual/en/functions.anonymous.php#example-195

Upvotes: 11

Related Questions