Search code examples
phplaravellaravel-passport

Laravel/Passport get guard user id


I using passport and I want to use for multiple auth so I done this by this topic , just I use name as agent instead of admin, what I trying to do now is get admin id.

Here is my code:

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

And:

public function handle($request, Closure $next)
{
    config(['auth.guards.api.provider' => 'agents']);
    return $next($request);
}

And:

Route::group(['middleware' => ['auth.agent']], function() {

So for getting id I tried:

return Auth::guard('Agent')->id;

Also with these names agent agents Agents

It return me a error:

Auth guard [Agents] is not defined

Sorry, I'm new to Laravel, any idea?

Edit: I also tried

php artisan config:clear  
php artisan config:cache

Solution

  • The guard you have setup has the name "agents" so this is how you should access it.

    What i think you have done is returned the SessionGuard object rather than your user model.

    Try these:

    return Auth::guard('agents')->check(); # true
    return Auth::guard('agents')->user()->id; # (int)
    

    Ammendment:

    In config/auth.php update the guards array

    'guards' => [
        'agents' => [
            'driver'   => 'session',
            'provider' => 'agents',
        ],
    ]
    

    OR: use Auth::guard('api')->user()->id