简体   繁体   中英

'Undefined variable' in Laravel 8 blade template on sending email

In my Laravel 8 project I try to send HTML e-mail, but get Undefined variable error.

I have this code in my controller:

// here the $client has a model value
Mail::to($client)->send(new ClientCreated($client));

In my app/Mail/ClientCreated.php file:

<?php

namespace App\Mail;

use App\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class ClientCreated extends Mailable
{
    use Queueable, SerializesModels;

    private $client;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // here the $this->client has a model value
        return $this->view('emails.client.created');
    }
}

Finally in my resources/views/emails/client/created.blade.php I have this code:

<p>Dear{{ $client->name }}!</p>

And I got this error message:

Undefined variable: client (View: /home/vagrant/Code/myproject/laravel/resources/views/emails/client/created.blade.php)

I read the docs and search on the Stackoverflow, but not found any help.

Any idea what I made wrong?

You should make $client public not private:

 public $client;

"There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view"

Laravel 8.x Docs - Mail - Writing Mailables - View Data - Via Public Properties

The other method would be calling with :

$this->view(...)->with('client', $this->client);

"If you would like to customize the format of your email's data before it is sent to the template, you may manually pass your data to the view via the with method."

Laravel 8.x Docs - Mail - Writing Mailables - View Data - Via the with Method

If you do not want to change $client to public then use the second method.

如果你正确地将变量传递给了视图,但它仍然不起作用,请尝试在控制台中重新启动队列:

php artisan queue:restart

You should make $client public

public $client;

Once the data has been set to a public property, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates. https://laravel.com/docs/8.x/mail#view-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM