3

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

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.