Laravel 5-运行时不工作时设置模型和表


Laravel 5 - Set Model and Table during Runtime Not Working

我正在为"student"answers"consulter"做两种不同类型的auth,因此是两个表。

到目前为止一切都很好。用户可以选择用户类型,然后登录,但当我在页面中打印{{Auth::user()['username]}}时,会出现错误:由于我在config/Auth.php中将模型和表指定为"student"answers"students",因此只能显示"student"名称。对于顾问用户,他们可以成功登录,但无法显示用户名。

我试着在运行时用config设置模型和表,但没有成功,下面是我的AuthController的一部分:

    if( $request->only('usertype')['usertype'] == 'student' ) {
        Config::set('auth.model','Student');
        Config::set('auth.table','students');
        $userprovider = new 'Illuminate'Auth'EloquentUserProvider(app('hash'), 'App'Student');
        Auth::setProvider($userprovider);
        $this->redirectPath = '/student/home';
    }
    else if( $request->only('usertype')['usertype'] == 'consultant' ) {
        Config::set('auth.model','Consultant');
        Config::set('auth.table','consultants');
        $userprovider = new 'Illuminate'Auth'EloquentUserProvider(app('hash'), 'App'Consultant');
        Auth::setProvider($userprovider);
        $this->redirectPath = '/consultant/home';
    }  $credentials = $this->getCredentials($request);      
    if (Auth::attempt($credentials, $request->has('remember'))) {
        return $this->handleUserWasAuthenticated($request, $throttles);
    }

Config::集似乎根本不起作用。可能是什么问题?我使用的是Laravel 5.1。

让我试着根据评论中jedrzej的解决方案来回答我的问题。

Config::set确实有效,但只有一次,并且需要针对每个身份验证请求进行修改。在这种情况下,使用中间件是一个理想的解决方案-在成功登录时将用户类型存储在会话中,然后在中间件中从会话中读取该值并设置配置变量-laravel.com/docs/master/middleware。

另一个更简单的解决方案是使用一些包进行多重身份验证。我使用了Sarav''Multiauth(https://packagist.org/packages/sarav/laravel-multiauth)而且效果非常好。