在 Laravel [php] 中将变量从控制器传递到可邮寄对象



在我的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');
}

我还创建了一个可邮寄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');
}
}

在我的欢迎电子邮件中,我需要访问一些变量,例如$toUserController中定义的

变量我在MyMail Mailable中尝试了以下内容:

public function build()
{
return $this->view('emails.welcome',['to' => $to]);
}

但我越来越Undefined variable: to

如何将变量从控制器传递到可邮寄对象?

更新:

到目前为止我尝试过:

用户控制器

Mail::to($to)->send(new MyMail($to));

我的邮件

public $to;
public function __construct($to)
{
$this->to = $to;
}
public function build()
{
return $this->view('emails.welcome');
}

欢迎光临.php

{{ $to }}

错误:

FatalErrorException in Mailable.php line 442:
[] operator not supported for strings

一种解决方案是将变量传递给MyMail构造函数,如下所示:

用户控制器

Mail::to($to)->send(new MyMail($to));

我的邮件

public $myTo;
public function __construct($to)
{
$this->myTo = $to;
}
public function build()
{
return $this->view('emails.welcome');
}

欢迎光临.php

{{ $myTo }}

更新:正如@Rahul在他的回答中指出的那样,$to属性可以定义为公共属性。在这种情况下,view将自动填充它。

更新2:您只需要为$to变量指定不同的名称(例如$myTo)以区别于Mailable.php中定义为public $to = [];$to

有两种方法可以使数据可用于视图。

  1. 首先,在可邮件类上定义的任何公共属性都将自动提供给视图
class MyMail extends Mailable
{
use Queueable, SerializesModels;
public $to;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($to)
{
$this->to = $to;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.welcome'); // $to will be automatically passed to your view
}
}
  1. 秒,您可以通过with方法手动将数据传递到视图,但您仍将通过可邮寄类传递数据" 构造 函数;但是,应将此数据设置为"受保护"或 私有属性,因此数据不会自动提供给 模板。
class MyMail extends Mailable
{
use Queueable, SerializesModels;
protected $to;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($to)
{
$this->to = $to;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.welcome',['to'=>$to]);

}
}

最新更新