【问题标题】:Push variable into a notification view on laravel将变量推送到 laravel 的通知视图中
【发布时间】:2019-03-27 08:53:30
【问题描述】:

我正在从 laravel 5.2 迁移到 5.3,我想在用户想要重置密码时发送自定义文本。 我现在看到,laravel 使用通知,默认的“主题”在 laravel 核心中是硬编码的。 我已经对此有一个视图(从 5.2 开始)并且通知可以使用自定义视图,所以我尝试了这个:

在 User.php(模型)中

/**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new SendLinkMailPasswordReset($token, $this->full_name));
    }

我创建通知“SendLinkMailPasswordReset”以“覆盖”laravel 和我的 toMail() 方法:

/**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->view('auth.emails.password')
                    ->with
                    (
                        [
                            'user'=> $this->full_name,
                            'token'=> $this->token,
                        ]
                    );
    }

如果我执行dd($this->full_name),它会起作用,但是当我重置密码时,我会得到Undefined variable: user

我不知道with 是否是正确的方法,或者我想这样做是否可行。 有关信息,如果我在我的 sendPasswordResetNotification 中这样做

public function sendPasswordResetNotification($token)
    { 
        $to=$this->email;
        $user= $this;

        Mail::send('auth.emails.password', ['user'=>$user, 'token'=>$token], function($message) use ($to) {
            $message->to($to)->subject('Reset your password'); 
        } );

    }

它有效。我使用通知是好的还是我应该推送邮件?

【问题讨论】:

标签: php laravel laravel-5.3


【解决方案1】:

试试这个

 $user = $this->full_name;
 $token = $this->token;

 return (new MailMessage)
                ->view('auth.emails.password', compact('user','token'));

像访问视图中的数据

{{ $user }}
{{ $token }}

【讨论】:

    【解决方案2】:

    另一种方式,我们可以像这样使用$viewData 属性(https://laravel.com/api/5.3/Illuminate/Notifications/Messages/MailMessage.html):

    $viewData=  [
                    'user'=>$this->full_name, 
                    'token'=>$this->token
                ];
    

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 2018-02-17
      • 2017-03-16
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2011-03-02
      相关资源
      最近更新 更多