如何在Laravel 5中对多个表使用身份验证


How to use authentication for multiple tables in Laravel 5

有时,我们希望在不同的2个表中分离用户和管理员
我认为这是一个很好的做法。

我想在《拉拉威尔5》中这是否可行。

在阅读以下内容之前,您应该具备Laravel 5中ServiceProvider、Facade和IoC的基本知识。我们开始吧。

根据Laravel的博士,你可以发现立面"Auth"指的是Illuminate'Auth'AuthManager,它有一个神奇的__call()。您可以看到主要功能不在AuthManager中,而是在Illuminate'Auth'Guard

Guard有一个提供程序。此提供程序具有$model属性,根据该属性,EloquentUserProvider将通过"new $model"创建此模型。这些都是我们需要知道的。代码来了。

1.我们需要创建一个AdminAuthServiceProvider

public function register(){
    Auth::extend('adminEloquent', function($app){
        // you can use Config::get() to retrieve the model class name from config file
        $myProvider = new EloquentUserProvider($app['hash'], ''App'AdminModel') 
        return new Guard($myProvider, $app['session.store']);
    })
    $app->singleton('auth.driver_admin', function($app){
        return Auth::driver('adminEloquent');
    });
}

2.立面:

class AdminAuth extends Facade {
        protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
    }

3.将别名添加到内核:

'aliases' => [
    //has to be beneath the 'Auth' alias
    'AdminAuth' => ''App'Facades'AdminAuth'
]

希望这能有所帮助。

我创建了一个laravel包,您可以在其中处理多重身份验证。

步骤1:Composer需要

首先,composer需要多身份包

composer require sarav/laravel-multiauth dev-master

步骤2:替换默认身份验证服务提供商

更换

Illuminate'Auth'AuthServiceProvider::class

带有

Sarav'Multiauth'MultiauthServiceProvider

在您的config/app.php文件中

步骤3:修改auth.php

将config/auth.php文件修改为类似以下的文件

'multi' => [
    'user' => [
        'driver' => 'eloquent',
        'model'  => App'User::class,
        'table'  => 'users'
    ],
'admin' => [
    'driver' => 'eloquent',
    'model'  => App'Admin::class,
    'table'  => 'admins'
   ]
],

就是这样!现在,您可以通过将用户作为第一个参数进行传递来尝试多重身份验证。例如

'Auth::loginUsingId("user", 1); // Login user with id 1
'Auth::loginUsingId("admin", 1); // Login admin with id 1
// Attempts to login user with email id johndoe@gmail.com 
'Auth::attempt("user", ['email' => 'johndoe@gmail.com', 'password' => 'password']);
// Attempts to login admin with email id johndoe@gmail.com
'Auth::attempt("admin", ['email' => 'johndoe@gmail.com', 'password' => 'password']); 

有关更多详细文档,

http://sarav.co/blog/multiple-authentication-in-laravel/

http://sarav.co/blog/multiple-authentication-in-laravel-continued/