有时,我们希望在不同的2个表中分隔用户和管理员.
我认为这是一个很好的做法.
所以我在寻找Laravel 5是否可行.
经过快速搜索,我发现很多人都有与我相同的问题.
我找到了一些答案,但我认为它们中的任何一个都不够好.
因此,我花了一些时间深入研究源代码,最后找到了实现这一目标的方法.
在阅读以下内容之前,您应该具备Laravel 5中ServiceProvider,Facade和IoC的基本知识.
根据Laravel的文档,你可以发现Facade'Auth'引用了它Illuminate\Auth\AuthManager,它有一个魔法__call().您可以看到主要功能不在AuthManager中,而是在Illuminate\Auth\Guard
Guard有一个提供者.此提供程序具有一个$model属性,根据该属性EloquentUserProvider将创建此模型"new $model".这些都是我们需要知道的.这是代码.
我们需要创造一个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');
});
}
Run Code Online (Sandbox Code Playgroud)
2.Facade:
class AdminAuth extends Facade {
protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
}
Run Code Online (Sandbox Code Playgroud)
3.将别名添加到内核:
'aliases' => [
//has to be beneath the 'Auth' alias
'AdminAuth' => '\App\Facades\AdminAuth'
]
Run Code Online (Sandbox Code Playgroud)
希望这可能会有所帮助.