Sau*_*abh 1 php laravel laravel-5.4
在我的UserController我有一个函数
public function userFollow($id)
{
$authuser = Auth::user();
$authuser->follow($id);
//mail goes to the followiee ($id)
$followiee = User::where('id', $id)->first();
$to = $followiee->email;
Mail::to($to)->send(new MyMail);
return redirect()->back()->with('message', 'Following User');
}
Run Code Online (Sandbox Code Playgroud)
我还创建了一个邮件 MyMail
class MyMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.welcome');
}
}
Run Code Online (Sandbox Code Playgroud)
在我的欢迎电子邮件中,我需要访问一些变量,例如$to在UserController
我在MyMail Mailable中尝试了以下操作:
public function build()
{
return $this->view('emails.welcome',['to' => $to]);
}
Run Code Online (Sandbox Code Playgroud)
但是我越来越 Undefined variable: to
如何将变量从Controller传递到Mailables?
更新:
到目前为止我尝试过的是:
用户控制器
Mail::to($to)->send(new MyMail($to));
Run Code Online (Sandbox Code Playgroud)
我的邮件
public $to;
public function __construct($to)
{
$this->to = $to;
}
public function build()
{
return $this->view('emails.welcome');
}
Run Code Online (Sandbox Code Playgroud)
Welcome.blade.php
{{ $to }}
Run Code Online (Sandbox Code Playgroud)
错误:
FatalErrorException in Mailable.php line 442:
[] operator not supported for strings
Run Code Online (Sandbox Code Playgroud)
一种解决方案是将变量传递给MyMail构造函数,如下所示:
用户控制器
Mail::to($to)->send(new MyMail($to));
Run Code Online (Sandbox Code Playgroud)
我的邮件
public $myTo;
public function __construct($to)
{
$this->myTo = $to;
}
public function build()
{
return $this->view('emails.welcome');
}
Run Code Online (Sandbox Code Playgroud)
Welcome.blade.php
{{ $myTo }}
Run Code Online (Sandbox Code Playgroud)
更新:
正如@Rahul在回答中指出的,该$to属性可以定义为public。在这种情况下,view将自动填充。
更新2:
你只需要提供一个不同的名称,以您的$to变量(例如$myTo)从区别$to中Mailable.php被定义为public $to = [];。