Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

php - How to use authentication for multiple tables in Laravel 5

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

I am looking if that is possible in Laravel 5.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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.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.Facade:

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

3. add the alias to Kernel:

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

Hope this could be helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...