Laravel通过Fortify自定义登录错误信息的实现方法
分情况显示邮箱/密码错误提示(Fortify实现)
1. 自定义认证动作类
创建自定义认证逻辑类,替换Fortify默认的认证动作,实现分别判断邮箱是否存在、密码是否正确:
在app/Actions/Fortify目录下新建AttemptToAuthenticate.php文件,内容如下:
<?php namespace App\Actions\Fortify; use Illuminate\Auth\AuthenticationException; use Illuminate\Support\Facades\Auth; use Laravel\Fortify\Actions\AttemptToAuthenticate as FortifyAttemptToAuthenticate; class AttemptToAuthenticate extends FortifyAttemptToAuthenticate { public function handle($request) { // 检查邮箱是否存在 $user = \App\Models\User::where('email', $request->email)->first(); if (!$user) { throw new AuthenticationException( '输入的邮箱不正确', [], route('login') ); } // 邮箱存在时验证密码 if (!Auth::guard($this->guard)->attempt( $request->only('email', 'password'), $request->filled('remember') )) { throw new AuthenticationException( '输入的密码不正确', [], route('login') ); } return tap(Auth::guard($this->guard)->user(), function ($user) use ($request) { $this->fireAuthenticatedEvent($request, $user); }); } }
2. 替换Fortify默认动作
打开app/Providers/FortifyServiceProvider.php,在boot方法中绑定自定义的认证动作,替换默认实现:
use App\Actions\Fortify\AttemptToAuthenticate; use Laravel\Fortify\Fortify; public function boot() { // 绑定自定义认证动作 $this->app->bind( \Laravel\Fortify\Actions\AttemptToAuthenticate::class, \App\Actions\Fortify\AttemptToAuthenticate::class ); // 其他Fortify配置代码... }
3. 在Blade视图中展示错误信息
在你的登录Blade视图里,添加错误信息展示代码:
@if ($errors->any()) <div class="alert alert-danger"> {{ $errors->first() }} </div> @endif
注意事项
- 如果你的用户模型使用的不是
email字段作为登录标识,需要修改自定义类中的查询条件。 - 该方法保留了Fortify默认的速率限制等功能,不会影响其他认证逻辑。
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

