【问题标题】:Laravel 5.4 EloquentUserProvider override validateCredentialsLaravel 5.4 EloquentUserProvider 覆盖 validateCredentials
【发布时间】:2017-10-19 13:19:09
【问题描述】:
public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

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

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

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以创建自己的 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'
    ),
    

    【讨论】:

      【解决方案2】:

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

      有关详细说明,请参阅this blog article。

      简称:

      首先,在您的 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',
          ],
      ],
      

      【讨论】:

      • 也在 Laravel 7 中工作
      猜你喜欢
      • 1970-01-01
      • 2017-10-27
      • 2020-05-27
      • 2019-02-22
      • 2017-08-30
      • 1970-01-01
      • 2017-11-27
      • 2018-04-25
      • 2018-04-08
      相关资源
      最近更新 更多