You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:40:33