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

如何通过Laravel Breeze禁用非活跃用户登录并强制登出?

Laravel Breeze 非活跃用户登录限制与强制登出实现方案

问题1:代码修改方案

1. 拦截非活跃用户登录(修改LoginRequest)

修改app\Http\Requests\Auth\LoginRequest.php的authenticate方法,在登录验证环节加入用户活跃状态检查:

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

    // 尝试登录时同时验证用户是否活跃
    $loginAttempt = Auth::attempt(
        array_merge($this->only('email', 'password'), ['active' => true]),
        $this->boolean('remember')
    );

    if (!$loginAttempt) {
        // 单独判断用户存在但非活跃的情况
        $user = \App\Models\User::where('email', $this->email)->first();
        if ($user && !$user->active) {
            RateLimiter::hit($this->throttleKey());
            throw \Illuminate\Validation\ValidationException::withMessages([
                'email' => '仅活跃用户可登录',
            ]);
        }

        // 其他登录失败场景
        RateLimiter::hit($this->throttleKey());
        throw \Illuminate\Validation\ValidationException::withMessages([
            'email' => trans('auth.failed'),
        ]);
    }

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

2. 强制已登录非活跃用户登出

创建自定义中间件来实时检查用户状态:

  1. 生成中间件:
php artisan make:middleware CheckUserActive
  1. 修改app/Http/Middleware/CheckUserActive.php:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckUserActive
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && !Auth::user()->active) {
            Auth::logout();
            return redirect()->route('login')->with('error', '你的账号已被禁用,请联系管理员');
        }

        return $next($request);
    }
}
  1. 在app/Http/Kernel.php的web中间件组中注册该中间件(放在Authenticate之后):
protected $middlewareGroups = [
    'web' => [
        // ... 其他已有中间件
        \App\Http\Middleware\Authenticate::class,
        \App\Http\Middleware\CheckUserActive::class, // 添加此行
    ],
];

问题2:自定义提示信息实现

完全可以实现专属提示,具体方式如下:

  • 登录拦截时:通过ValidationException直接返回'仅活跃用户可登录',会自动显示在登录页面的email字段下方
  • 强制登出时:通过with('error')传递提示信息,需要在登录页面添加错误展示代码,修改resources/views/auth/login.blade.php:
@if(session('error'))
    <div class="alert alert-danger">
        {{ session('error') }}
    </div>
@endif

内容的提问来源于stack exchange,提问作者David Gabbay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:35:30