发送电子邮件时 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 AppMail;
use AppClient;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
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上搜索,但没有找到任何帮助。

知道我做错了什么吗?

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

php artisan queue:restart

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

public $client;

"有两种方法可以使数据可用于视图。首先,在您的mailable类上定义的任何公共属性都将自动对视图"可用;

Laravel 8.x文档-邮件-编写可邮件-查看数据-通过公共属性

另一种方法是调用with:

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

"如果您希望在将电子邮件数据发送到模板之前自定义其格式,则可以通过with方法手动将数据传递到视图">

Laravel 8.x文档-邮件-编写可邮件-查看数据-通过with方法

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

您应该将$client公开为

public $client;

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

最新更新