【问题标题】:Variables are not passed in the email template变量未在电子邮件模板中传递
【发布时间】:2019-07-25 00:54:04
【问题描述】:

我的控制器中有这个方法

public function update(UserUpdateRequest $request)
{
        $request->user()->update([
            'name' => $request->username,
        ]);

        Mail::to($request->user())->send(
            new UserUpdated( $request->user() )
        );

        return redirect()->route('account.index');
}

所以当用户更新用户名时会发送一封电子邮件

public $user;

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

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->markdown('emails.user.updated');
}

这是电子邮件模板

Hi {{ $user->username }},

We would like to inform you that your username has been updated successfully. 

If this action wasn't done by you, you need to contact with our support.

但这会在队列中抛出异常

ErrorException:未定义变量:/storage/framework/views/ 中的用户

任何想法我做错了什么?

【问题讨论】:

  • 不能这样声明:$this->property = $something;
  • 但它与文档laravel.com/docs/5.8/mail#view-data中的几乎相同
  • 你能通过with方法试试吗?
  • 已经尝试过了,但没有运气。我在构造函数中 dd($user) 和 dd($this->user) 并传递了用户数据,但是它们在模板中不可用,这很奇怪

标签: laravel email laravel-5 markdown


【解决方案1】:

尝试通过with 方法将其传递给view 并使user 变量受保护:

protected $user;

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

然后你就可以在你的视图中像{{ $username }}一样访问它。

【讨论】:

  • 已经尝试过了,但没有运气。我在构造函数中 dd($user) 和 dd($this->user) 并传递了用户数据,但是它们在模板中不可用,这很奇怪
  • 您确定您使用的是view 而不是markdown
  • 是的,我按照文档中的步骤进行操作
【解决方案2】:

试试这个,然后在你的视图中访问 $user

public function update(UserUpdateRequest $request)
{
    $request->user()->update([
        'name' => $request->username,
    ]);

    $user = $request->user();

    Mail::to($request->user())
        ->send(new UserUpdated($user));

    return redirect()->route('account.index');
}

您无法直接向您的电子邮件模板发送 $request,这可能是您无法访问 $user 的原因

【讨论】:

    猜你喜欢
    • 2019-08-23
    • 2015-12-11
    • 1970-01-01
    • 2015-09-02
    • 2016-10-20
    • 2014-03-29
    • 1970-01-01
    • 2011-11-30
    • 2018-02-06
    相关资源
    最近更新 更多