将变量推送到Laravel通知视图中

4
我正在从laravel 5.2迁移到5.3版本,希望在用户想要重置密码时发送自定义文本。 现在我发现,laravel使用通知(Notification),默认的“主题(theme)”是硬编码在laravel核心代码中的。 我已经有了一个视图(来自5.2),并且通知可以使用自定义视图,因此我尝试了以下内容:
在User.php(Model)中:
/**
     * 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()方法:

我在这里重写了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'); 
        } );

    }

它起作用了。我的通知使用是否恰当,或者在我的情况下我应该发送电子邮件而不是推送通知?


仅在下一个请求之前使用,它使用Flash会话。 - Vikash
谢谢您的回复。当我阅读文档 https://laravel.com/api/5.3/Illuminate/Notifications/Messages/MailMessage.html#method_with 时,它说“向通知添加一行文本。”这就是为什么我使用它的原因。您知道其他方法吗? - MisterDebug
2个回答

8

试试这个

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

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

可以像这样访问视图中的数据:

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

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接