Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 568
José Carlos Ribeiro Avatar asked Apr 07 '26 12:04

José Carlos Ribeiro


1 Answers

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

like image 69
Steve Avatar answered Apr 09 '26 01:04

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!