Laravel 5.4 EloquentUserProvider覆盖validateCredentials

时间:2017-05-19 11:59:17

标签: laravel

public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

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

如何覆盖类validateCredentials中的方法EloquentUserProvider?谢谢!

2 个答案:

答案 0 :(得分:18)

在Laravel 5.4中,您无需在 config / app.php 中注册 CustomUserProvider

首先,在 Providers 目录中创建 CustomUserProvider.php 文件:

<?php

namespace App\Providers;

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


class CustomUserProvider extends UserProvider {

    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

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

}

在此之后,更改 AuthServiceProvider.php 文件中的boot()方法:

public function boot()
{
    $this->registerPolicies();

    \Illuminate\Support\Facades\Auth::provider('customuserprovider', function($app, array $config) {
        return new CustomUserProvider($app['hash'], $config['model']);
    });
}

现在,您可以通过将驱动程序名称添加到 config / auth.php 文件来使用提供程序:

'providers' => [
    'users' => [
        'driver' => 'customuserprovider',
        'model' => App\User::class,
        'table' => 'users',
    ],
],

答案 1 :(得分:3)

您可以创建自己的UserProvider,然后可以覆盖原始UserProvider中的功能。

首先创建CustomUserProvider:

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

class CustomUserProvider extends UserProvider {

  public function validateCredentials(UserContract $user, array $credentials)
  {
    $plain = $credentials['password'];

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

}

然后在config / app.php

中注册新的CustomUserProvider
'providers' => array(
   ... On the bottom, must be down to override the default UserProvider
   'Your\Namespace\CustomUserProvider'
),