[英]'Undefined variable' in Laravel 8 blade template on sending email
在我的 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;
“您可以通过两种方式将数据提供给您的视图。首先,您的可邮寄类中定义的任何公共属性都将自动提供给视图”
Laravel 8.x 文档 - 邮件 - 编写邮件 - 查看数据 - 通过公共属性
另一种方法将调用with
:
$this->view(...)->with('client', $this->client);
“如果您想在发送到模板之前自定义电子邮件数据的格式,您可以通过
with
方法手动将数据传递到视图。”
Laravel 8.x 文档 - 邮件 - 编写邮件 - 查看数据 - 通过with
方法
如果您不想将$client
更改$client
public
则使用第二种方法。
如果你正确地将变量传递给了视图,但它仍然不起作用,请尝试在控制台中重新启动队列:
php artisan queue:restart
你应该公开 $client
public $client;
一旦数据被设置为公共属性,它将自动在您的视图中可用,因此您可以像访问 Blade 模板中的任何其他数据一样访问它。 https://laravel.com/docs/8.x/mail#view-data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.