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

Laravel 5.6自定义Physiotherapists表API认证:Auth::attempt验证失败求助

解决Laravel 5.6中自定义认证表的Auth::attempt验证问题

你已经完成了自定义认证表的基础配置,但Auth::attempt失效的问题主要出在Guard的指定和密码哈希这两个核心点上,下面一步步帮你解决:

1. 必须明确指定使用api Guard进行验证

默认情况下,Auth::attempt()会自动使用web Guard(也就是配置里的第一个Guard),而你的web Guard对应的Provider还是users,所以哪怕你传入的是physiotherapists表的信息,它依然会去users表查询,自然验证失败。

你需要显式指定使用api Guard来验证:

$credentials = [
    'email' => request('email'),
    'password' => request('password')
];

if (Auth::guard('api')->attempt($credentials)) {
    // 验证通过后的逻辑,比如生成API令牌
    $user = Auth::guard('api')->user();
    $token = $user->createToken('PhysioAPIToken')->accessToken;
    return response()->json(['token' => $token], 200);
} else {
    return response()->json(['error' => 'Unauthorized'], 401);
}

2. 确保注册时密码已被哈希存储

Auth::attempt()会自动将传入的明文密码与数据库中哈希后的密码进行比对,如果你的physiotherapists表中存储的是明文密码,验证肯定会失败(哪怕是users表的信息,如果是明文也无法通过验证)。

在注册Physiotherapist时,一定要用Hash::make()加密密码:

use Illuminate\Support\Facades\Hash;

// 注册逻辑示例
$physio = Physiotherapist::create([
    'email' => request('email'),
    'password' => Hash::make(request('password')),
    // 其他必填字段
]);

3. 完善模型的基础配置

虽然你的模型已经继承了Authenticatable,但为了避免歧义,建议补充以下配置:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;

class Physiotherapist extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // 明确指定表名(虽然Laravel默认会复数化模型名,但显式指定更稳妥)
    protected $table = 'physiotherapists';

    // 允许批量赋值的字段,确保email和password在列中
    protected $fillable = [
        'email', 'password', // 其他字段根据你的表结构添加
    ];

    // 如果你的主键不是默认的`id`,需要指定
    // protected $primaryKey = 'physio_id';

    public function patients()
    {
        return $this->hasMany('App\Patient');
    }
}

4. 确认Laravel Passport的配置完整性

因为你的api Guard使用的是passport驱动,要确保你已经完成了Passport的安装和配置:

  • 运行过composer require laravel/passport
  • 执行过php artisan migrate生成Passport相关表
  • 在AuthServiceProvider中注册了Passport路由:
    use Laravel\Passport\Passport;
    
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
    }
    
  • 已经运行过php artisan passport:install生成加密密钥

完成以上步骤后,你的Auth::attempt应该就能正常验证physiotherapists表的用户信息了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:31:18