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

重写Laravel Eloquent用户提供者触发TypeError错误求助

Laravel自定义UserProvider构造函数类型错误排查与修复

错误信息

TypeError: App\Providers\AuthUserProvider::__construct(): Argument #1 ($hasher) must be of type Illuminate\Contracts\Hashing\Hasher, Illuminate\Foundation\Application given, called in /var/www/apirenatre-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php on line 849 in file /var/www/apirenatre-laravel/app/Providers/AuthUserProvider.php on line 13

问题原因分析

  1. 配置文件键名错误:config/auth.php中自定义提供者使用了table键而非model键,导致$config['model']取值为空,框架解析时触发异常,进而引发参数传递错误。
  2. 用户模型未适配密码字段:默认getAuthPassword()方法返回password字段,但你的表中密码字段为user_password,即使修复类型错误,最终认证也会失败。
  3. 自定义Provider冗余代码:重复定义$hasher属性及构造函数赋值,虽不直接引发错误,但不符合Laravel继承规范。

解决方案

1. 修复认证配置文件

修改config/auth.php中providers下的自定义提供者配置,将table改为model:

'user_provider_custom' => [
    'driver' => 'auth_user_provider_custom',
    'model' => App\Models\User::class,
],

2. 清理配置缓存

执行命令清除配置缓存,确保新配置生效:

php artisan config:clear

3. 重写用户模型的密码字段方法

在App\Models\User.php中添加getAuthPassword()方法,返回自定义密码字段:

public function getAuthPassword()
{
    return $this->user_password;
}

4. 简化自定义UserProvider代码

删除冗余的$hasher属性和构造函数赋值,直接继承父类的实现:

namespace App\Providers;

use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;

class AuthUserProvider extends EloquentUserProvider
{
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['user_password'] ?? null;
        if (is_null($plain)) {
            return false;
        }

        return $this->hasher->check($plain, $user->getAuthPassword());
    }
}

验证

完成上述修改后,尝试登录认证,类型错误应已解决,且能正确验证user_password字段的密码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:39:50