如何在Laravel 9 Breeze中校验用户表approved字段以限制未审核用户登录
在Laravel 9 Breeze中实现登录校验
approved字段 步骤1:确认数据库字段配置
确保users表的approved字段已正确创建,迁移文件示例如下:
Schema::table('users', function (Blueprint $table) { $table->boolean('approved')->default(0)->index(); });
执行迁移命令后,验证字段已成功添加到数据表中。
步骤2:修改登录认证逻辑
找到app/Http/Requests/Auth/LoginRequest.php文件,修改其中的authenticate()方法,实现审核状态校验:
方式一:认证时直接校验审核状态
在账号密码验证阶段,直接加入approved=1的条件,仅允许已审核用户通过认证:
public function authenticate() { $this->ensureIsNotRateLimited(); // 合并审核状态条件到认证参数 $credentials = array_merge($this->only('email', 'password'), ['approved' => 1]); if (! Auth::attempt($credentials, $this->boolean('remember'))) { RateLimiter::hit($this->throttleKey()); // 区分错误类型:账号未审核/密码错误 $user = \App\Models\User::where('email', $this->email)->first(); $errorMsg = $user && !$user->approved ? '你的账号尚未通过审核,无法登录。' : trans('auth.failed'); throw ValidationException::withMessages([ 'email' => $errorMsg, ]); } RateLimiter::clear($this->throttleKey()); }
方式二:认证后校验审核状态
先验证账号密码正确性,再检查用户审核状态,若未审核则强制登出并提示:
public function authenticate() { $this->ensureIsNotRateLimited(); if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) { RateLimiter::hit($this->throttleKey()); throw ValidationException::withMessages([ 'email' => trans('auth.failed'), ]); } // 认证成功后检查审核状态 if (!auth()->user()->approved) { auth()->logout(); RateLimiter::hit($this->throttleKey()); throw ValidationException::withMessages([ 'email' => '你的账号尚未通过审核,无法登录。', ]); } RateLimiter::clear($this->throttleKey()); }
步骤3:(可选)本地化错误提示
若需多语言支持,可在resources/lang/zh-CN/auth.php中添加自定义提示:
return [ // ... 原有提示 'not_approved' => '你的账号尚未通过审核,无法登录。', ];
之后将代码中的提示文本替换为trans('auth.not_approved')即可。
内容的提问来源于stack exchange,提问作者Дима
相关产品推荐
相关产品推荐

