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

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

问题描述

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

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

我正在寻找在 Laravel 5 中是否可行.

I am looking if that is possible in Laravel 5.

推荐答案

在阅读以下内容之前,您应该对 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' 指的是 IlluminateAuthAuthManager,它有一个神奇的 __call().您可以看到主要功能不在 AuthManager 中,而是在 IlluminateAuthGuard

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

Guard 有一个 Provider.这个提供者有一个 $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'], 'AppAdminModel') 
        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' => 'AppFacadesAdminAuth'
]

希望这会有所帮助.

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

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