[英]'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.