Laravel 8自定义mobile guard报错Auth guard[] is not defined如何解决
问题原因及解决方案
1. 首要语法错误
你控制器里的认证代码存在语法问题,数组的password键未加引号,高版本PHP会直接抛出语法错误:
原错误代码:
Auth::guard('mobile')->attempt(['email'=>'testmail@test.com',password=>'password']);
修正为:
Auth::guard('mobile')->attempt(['email' => 'testmail@test.com', 'password' => 'password']);
2. Technician模型继承错误排查
自定义guard对应的用户模型必须继承Laravel提供的认证基类,而非默认的Model基类,否则会触发认证逻辑报错,请确认你的App\Models\Technician模型符合以下定义:
namespace App\Models; // 需继承Authenticatable基类,不要直接继承Illuminate\Database\Eloquent\Model use Illuminate\Foundation\Auth\User as Authenticatable; class Technician extends Authenticatable { // 可按需求修改填充、隐藏字段 protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
3. 其他常规排查项
- 若你在路由中使用
auth中间件保护接口,必须明确指定guard,否则默认走webguard,示例:Route::middleware('auth:mobile')->group(function () { // 需要mobile guard认证的路由 }); - 确认
technicians表中对应用户的password字段是通过bcrypt()或Hash::make()方法哈希存储的,attempt方法会自动对传入的明文密码做哈希比对,明文存储的密码无法通过验证。 - 可执行完整缓存清理命令,避免各类缓存导致配置不生效:
php artisan config:clear php artisan cache:clear php artisan route:clear
内容的提问来源于stack exchange,提问作者user16780021
相关产品推荐
相关产品推荐

