Laravel 5.4 EloquentUserProvider override validateCredentials

后端 未结 2 1681
我在风中等你
我在风中等你 2020-12-14 13:00
public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials[\'password\'];

        return $this->hasher->c         


        
相关标签:
2条回答
  • 2020-12-14 13:47

    You can create your own UserProvider and then you can override the functions from the original UserProvider.

    First you create the 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());
      }
    
    }
    

    Then you register your new CustomUserProvider in config/app.php

    'providers' => array(
       ... On the bottom, must be down to override the default UserProvider
       'Your\Namespace\CustomUserProvider'
    ),
    
    0 讨论(0)
  • 2020-12-14 13:51

    In Laravel 5.4 you don't need to register your CustomUserProvider in config/app.php.

    See this blog article for detailed instructions.

    The short form:

    First, create a CustomUserProvider.php file in your Providers directory:

    <?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());
        }
    
    }
    

    After this, change the boot() Method in your AuthServiceProvider.php file:

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

    Now, you can use the provider by adding the driver name to your config/auth.php file:

    'providers' => [
        'users' => [
            'driver' => 'customuserprovider',
            'model' => App\User::class,
            'table' => 'users',
        ],
    ],
    
    0 讨论(0)
提交回复
热议问题