微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

发送电子邮件时,Laravel 8刀片服务器模板中的“未定义变量”

如何解决发送电子邮件时,Laravel 8刀片服务器模板中的“未定义变量”

在Laravel 8项目中,我尝试发送HTML电子邮件,但出现Undefined variable错误

我的控制器中有以下代码

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

在我的app/Mail/ClientCreated.PHP文件中:

<?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');
    }
}

最后在我的resources/views/emails/client/created.blade.PHP中,我有以下代码

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

我收到此错误消息:

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

我阅读了文档并在Stackoverflow上进行搜索,但没有找到任何帮助。

知道我做错了什么吗?

解决方法

您应将$client设为公开而非私有:

 public $client;

“有两种方法可以使数据对视图可用。首先,可邮递类上定义的任何 public 属性将自动对视图可用”

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

另一种方法是调用with

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

“如果要在将电子邮件数据发送到模板之前自定义其格式,可以通过with方法将数据手动传递到视图。”

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

如果您不想将$client更改为public,请使用第二种方法。

,

您应该将$ client公开

public $client;

将数据设置为公共属性后,它将在您的视图中自动可用,因此您可以像访问Blade模板中的任何其他数据一样访问它。 https://laravel.com/docs/8.x/mail#view-data

,

如果你把变量正确的传递给了视图,但是还是不行,尝试在控制台重启队列:

php artisan queue:restart

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。