如何在Laravel 5中对多个表使用身份验证 [英] How to use authentication for multiple tables in Laravel 5

查看:54
本文介绍了如何在Laravel 5中对多个表使用身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我们希望将用户和管理员分开放在两个不同的表中.
我认为这是一个好习惯.

Sometimes, we'd like to separate users and admins in different 2 tables.
I think it is a good practice.

所以我一直在寻找Laravel 5中是否有可能.

So I was looking if that is possible in Laravel 5.

快速搜索后,我发现许多人与我的问题相同.
我找到了一些答案,但我认为其中的任何一个都不够好.

After a quick search, I found many people having the same question as mine.
I found some answers, but I don't think any of them is good enough.

因此,我花了一些时间研究源代码,终于找到了实现此目标的方法.

Therefore, I spent some time digging into the source code and finally find a way to achieve this.

推荐答案

在阅读以下内容之前,您应该已经了解Laravel 5中的ServiceProvider,Facade和IoC的基本知识.

Before reading the following, you are supposed to have basic knowledge on ServiceProvider, Facade and IoC in Laravel 5. Here we go.

根据Laravel的文档,您可以发现Facade的"Auth"引用的是Illuminate\Auth\AuthManager,它具有一个神奇的__call().您可以看到主要功能不是在 AuthManager 中,而是在Illuminate\Auth\Guard

According to the doc of Laravel, you could find the Facade 'Auth' is refering to the Illuminate\Auth\AuthManager, which has a magic __call(). You could see the major function is not in AuthManager, but in Illuminate\Auth\Guard

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

Guard has a Provider. This provider has a $model property, according to which the EloquentUserProvider would create this model by "new $model". These are all we need to know. Here goes the code.

1.我们需要创建一个AdminAuthServiceProvider.

1.We need to create a 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.将别名添加到内核:

3. add the alias to Kernel:

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

希望这会有所帮助.

这篇关于如何在Laravel 5中对多个表使用身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆