Ad

Laravel 5 - Set Model And Table During Runtime Not Working

- 1 answer

I am doing two different types of auth for 'student' and 'consultant', thus two tables.

So far everything works fine. A user can choose usertype and then login, but when I'm printing {{ Auth::user()['username'] }} in the page error occurs: only 'student' name can be displayed, since I specified model and table in config/auth.php to be 'Student' and 'students'. As for consultant users, they can successfully login, but username can't be displayed.

I tried to set model and table with config during runtime but doesn't work, here's part of my 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);
    }

Seems the Config::set doesn't work at all. What could be the problem? I'm using Laravel 5.1.

Ad

Answer

Let me try answering my question, based on jedrzej's solution in the comment.

Config::set did work, but only for once and needs to be modified for every request for authentication. In this case, doing a middleware is an ideal solution - store user type in session on successful login and then in the middleware read that value from session and set config variables - laravel.com/docs/master/middleware.

Another easier solution is using some package for multi-auth. I used Sarav\Multiauth (https://packagist.org/packages/sarav/laravel-multiauth) and it works perfectly.

Ad
source: stackoverflow.com
Ad