pass variable from Laravel mailable class to view

时间:2018-02-26 18:00:35

标签: laravel-5.4

I need to pass user object and a password to Laravel mailable class. I've tried so many ways, nothings seems to work. Here's my latest attempt.

Password is passed into payload properly.

Controller

Mail::to($user)
            ->queue(new EmployeeCreated($password));

Mailable

class EmployeeCreated extends Mailable
{
    use Queueable, SerializesModels;

    public $password;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($password)
    {
        $this->password = $password;
        $password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->subject('YOU ARE IN!')
            ->view('mail.employees.created')
            ->withPassword($password);
    }
}

View

You got your account. Got to {{url('/login')}}. Use e-mail as username. Your password is {{$password}}.

Error message

ErrorException: Undefined variable: password in /var/www/html/storage/framework/views/4c04e63464617b1ec451525800e71aa14d7540d4.php:1

3 个答案:

答案 0 :(得分:1)

直接将它们作为类型提示构造函数参数传递,您不限于可以定义的数量。将访问修饰符设置为public:

public $user;

public $password;

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct(User $user, $password)
{
    $this->user = $user;
    $this->password = $password;
}
  

您的mailable类中定义的所有公共属性都将自动提供给视图。

Docs

答案 1 :(得分:0)

您可以在Mailable lyke中显式传递变量:

...

public function build()
{
    return $this->view('emails.myview')->with(['variable' => $this->variable]);
}

...

答案 2 :(得分:0)

我认为构建函数中的问题 试试

public function build()
{
    return $this
        ->subject('YOU ARE IN!')
        ->view('mail.employees.created')
        ->with('Password',$password);
}