如何让Laravel Fortify为管理员和用户生成不同的重置密码链接?
解决方案:区分管理员与用户的密码重置链接
问题根源在于Laravel Fortify默认使用统一的ResetPassword通知类生成重置链接,不会区分用户角色或请求来源。要实现不同角色的专属重置链接,需要自定义通知逻辑并根据角色分发。
步骤1:创建管理员专属密码重置通知类
新建AdminPasswordResetNotification类,专门生成带/admin前缀的重置链接:
// app/Notifications/AdminPasswordResetNotification.php namespace App\Notifications; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; use Illuminate\Support\Facades\Lang; class AdminPasswordResetNotification extends Notification { protected $token; public function __construct(string $token) { $this->token = $token; } public function via($notifiable): array { return ['mail']; } public function toMail($notifiable): MailMessage { $resetUrl = route('admin.password.reset', [ 'token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset(), ], false); return (new MailMessage) ->subject(Lang::get('Reset Password Notification')) ->line(Lang::get('You are receiving this email because we received a password reset request for your admin account.')) ->action(Lang::get('Reset Password'), $resetUrl) ->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.' . config('auth.defaults.passwords') . '.expire')])) ->line(Lang::get('If you did not request a password reset, no further action is required.')); } }
步骤2:在User模型中重写通知分发逻辑
利用Spatie Laravel-Permission的角色判断方法,在User模型中重写sendPasswordResetNotification,根据用户角色选择对应的通知:
// app/Models/User.php use App\Notifications\AdminPasswordResetNotification; use Illuminate\Auth\Notifications\ResetPassword; public function sendPasswordResetNotification($token): void { if ($this->hasRole('admin')) { $this->notify(new AdminPasswordResetNotification($token)); } else { $this->notify(new ResetPassword($token)); } }
步骤3:修复Fortify重置密码视图的判断逻辑
之前的resetPasswordView方法报错是因为没有正确识别路由,改用路由名称判断更可靠:
// app/Providers/FortifyServiceProvider.php Fortify::resetPasswordView(function (Request $request) { if ($request->route()->getName() === 'admin.password.reset') { return view('auth.admin.reset-password', ['request' => $request]); } return view('auth.reset-password', ['request' => $request]); });
验证效果
- 管理员提交密码重置请求时,会收到带
/admin/reset-password/token的链接 - 普通用户提交时,收到标准的
/reset-password/token链接 - 点击对应链接会跳转到各自的重置密码页面
内容的提问来源于stack exchange,提问作者user21640841
相关产品推荐
相关产品推荐

