fightstarr20
fightstarr20

Reputation: 12588

Laravel 5.6 - Can't pass variable to email view

I have setup a mailer in a Laravel 5.6 app but am struggling to pass variables to the view, my welcome.php controller looks like this..

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class Welcome extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct()
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome');
    }
}

Any my view looks like this..

Your registered email-id is {{$user->email}}

I am calling the email controller after a user is created like this...

$user->save();
Mail::to($user->email)->send(new Welcome($user));

I am getting an error message telling me that undefined variable: user

Where am I going wrong?

Upvotes: 1

Views: 505

Answers (2)

J. Doe
J. Doe

Reputation: 1732

Edit tour mail file

public function __construct($user)
{
    $this->user = $user;
}

public function build()
{
    return $this->view('emails.welcome')->with(['user' => $this->user]);
}

Upvotes: 2

Chin Leung
Chin Leung

Reputation: 14921

Your constructor is not accepting any variable...

public function __construct()
{
    $this->user = $user;
}

Change it to:

public function __construct($user)
{
    $this->user = $user;
}

Or you can type hint it like this:

use App\User;


...


public function __construct(User $user)
{
    $this->user = $user;
}

Upvotes: 3

Related Questions