Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Laravel 5 User class properties not accessible for sending Email after account creation

I have a problem where I can't put in the variables into the Mail::send() function in laravel. Please see the following code:

$first_name = $request->input('first_name'),
$email = $request->input('email'),

//Create account

User::create([
    'first_name' => $first_name,
    'last_name' => $request->input('last_name'),
    'email' => $email,
    'password' => bcrypt($request->input('password')),
]);

//Send email to user

Mail::send('emails.test', ['fname' => $first_name], function($message)
{
    $message->to($email)
            ->subject('Welcome!');
});

return redirect()
    ->route('home')
    ->with('info', 'Your account has been created and an authentication link has been sent to the email address that you provided. Please go to your email inbox and click on the link in order to complete the registration.');

For some reason the code breaks when it gets to the send email because I receive the error and the data is sent to the database. Why is the variable no longer accessible afterwards?

Any help would be greatly appreciated. Thank you

like image 501
PHP beginner Avatar asked Nov 19 '25 18:11

PHP beginner


1 Answers

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

Source: http://php.net/manual/en/functions.anonymous.php

In other words, $email has to be inherited like this:

Mail::send('emails.test', ['fname' => $first_name], function($message) use ($email)
{
    $message->to($email)
            ->subject('Welcome!');
});

Note: use ($email) in the first line.

like image 123
Thomas Kim Avatar answered Nov 22 '25 09:11

Thomas Kim



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!