Laravel自定义邮箱验证模板添加用户名遇Auth用户获取异常问题
Laravel邮箱验证邮件添加用户名的问题解决
问题描述
在AuthServiceProvider的boot方法中自定义邮箱验证邮件内容时,尝试用Auth::user()->name获取用户名,出现以下异常:
- 新用户注册后直接跳转验证页面时,调用
Auth::user()会报错(无法获取用户实例) - 关闭页面从登录页重新登录后,却能正常获取到用户信息
当前代码:
public function boot() { $this->registerPolicies(); VerifyEmail::toMailUsing(function ($notifiable, $url) { $user_name = Auth::user()->name; return (new MailMessage) ->greeting("Hello {$user_name}!") ->subject('Verify Email Address') ->line('Please click the button below to verify your email address.') ->action('Verify Email Address', $url) ->line('If you did not create an account, no further action is required.'); }); }
问题原因
注册流程中发送验证邮件的时机,用户会话尚未完全建立,此时Auth::user()无法获取到当前用户实例(返回null),所以调用->name会触发错误。而登录后会话已存在,Auth::user()能正常获取用户对象。
解决方法
toMailUsing回调函数的第一个参数$notifiable本身就是当前的用户模型实例,直接通过它获取用户名即可,无需依赖会话:
修改后的代码:
public function boot() { $this->registerPolicies(); VerifyEmail::toMailUsing(function ($notifiable, $url) { // 直接使用$notifiable获取用户名,无需Auth::user() $user_name = $notifiable->name; return (new MailMessage) ->greeting("Hello {$user_name}!") ->subject('Verify Email Address') ->line('Please click the button below to verify your email address.') ->action('Verify Email Address', $url) ->line('If you did not create an account, no further action is required.'); }); }
说明
$notifiable是Laravel通知系统自动传递的目标模型对象,这里对应刚注册的用户实例- 这种方式不依赖用户会话状态,无论注册时还是登录后发送验证邮件,都能正常获取用户信息
内容的提问来源于stack exchange,提问作者Wakil Ahmed
相关产品推荐
相关产品推荐

