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

Laravel 8 + Breeze 登录时校验用户active字段仅允许活跃用户登录

Laravel 8 Breeze 登录校验active字段实现方案

你猜测校验逻辑放在AuthenticatedSessionController的store方法内的思路是可行的,以下提供两种实现方式:

注意:两种方案二选一即可,无需同时修改代码。


方案1:直接在store方法中追加校验

修改app/Http/Controllers/Auth/AuthenticatedSessionController.php的store方法:

public function store(LoginRequest $request)
{
    $request->authenticate();

    // 追加active字段校验
    if (Auth::user()->active != 1) {
        // 不符合条件直接登出清除登录状态
        Auth::logout();
        // 返回登录页携带错误提示
        return redirect()->route('login')->withErrors([
            'email' => '当前账号已被禁用,请联系管理员处理'
        ]);
    }

    $request->session()->regenerate();

    return redirect()->intended(RouteServiceProvider::HOME);
}

逻辑说明:$request->authenticate()执行完成后,用户账号密码已经校验通过,此时可以直接通过Auth::user()获取登录用户信息,判断active字段值即可。


方案2:修改LoginRequest验证逻辑(推荐,符合Laravel原生设计规范)

该方案将active=1作为登录凭证校验的前置条件,不需要在登录后再做登出操作,逻辑更连贯。
找到app/Http/Requests/Auth/LoginRequest.php文件,修改内置的authenticate方法:

public function authenticate()
{
    $this->ensureIsNotRateLimited();

    // 先判断账号是否被禁用,区分错误提示
    $user = \App\Models\User::where('email', $this->email)->first();
    if ($user && $user->active != 1) {
        throw \Illuminate\Validation\ValidationException::withMessages([
            'email' => '当前账号已被禁用,请联系管理员处理'
        ]);
    }

    // 校验账号密码正确性
    if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());

        throw \Illuminate\Validation\ValidationException::withMessages([
            'email' => trans('auth.failed'),
        ]);
    }

    RateLimiter::clear($this->throttleKey());
}

逻辑说明:Laravel的Auth::attempt方法默认会将传入的所有数组字段作为用户表查询条件,你也可以直接在attempt参数中追加['active' => 1]快速实现过滤,只是错误提示会和账号密码错误的提示一致,无法区分禁用场景。


内容的提问来源于stack exchange,提问作者Charles Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:09:00