Multiple User Models Laravel JWT Auth

Posting for anyone who finds this questions

Although it's not recommended to have two user tables, but I had a similar requirement of setting up JWT with one of our clients. This is how I solved the issue.

No need to make any changes to the providers in `config/auth.php'

'providers' => [
    'users' => [
        'driver' => 'eloquent',
           'model' => App\User::class,
     ],

]

In your authentication controller, dynamically modify the model used by the providers by setting

\Config::set('auth.providers.users.model', \App\Trainer::class);

Example code

In authenticate() method

if ($credentials['user_type'] == 'consultant') {

\Config::set('auth.providers.users.model', \App\Trainer::class);

} else {
    \Config::set('auth.providers.users.model', \App\User::class);
}

//Find the user

//Create the token
if ($user) {
   $customClaims = ['user_type' => $credentials['user_type']];
   $token = JWTAuth::fromUser($user,$customClaims);
} else {
  return response()->json(['error' => 'invalid_credentials'], 401);
}

You will have to do the same while parsing the token to authenticate the user as well. Example code

In getAuthenticatedUser() method

$payload = JWTAuth::parseToken()->getPayload();
$user_type = $payload->get('user_type');

if($user_type === 'consultant'){
   \Config::set('auth.providers.users.model', \App\Trainer::class);
}else{
   \Config::set('auth.providers.users.model', \App\User::class);
}

if (!$user = JWTAuth::parseToken()->authenticate()) {
    return response()->json(['user_not_found'], 404);
}

Tags:

Php

Laravel

Jwt