Babaev
Babaev

Reputation: 253

How to get ID of authorized user in jwt-auth?

How to get ID of authorized user in jwt-auth? I tried to get id by standart method, but it does not work

Upvotes: 2

Views: 8044

Answers (1)

baikho
baikho

Reputation: 5368

When using jwt-auth you can get the user ID by parsing the JWT token:

public function getAuthenticatedUser()
{
    try {
        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }
    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
        return response()->json(['token_expired'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
        return response()->json(['token_invalid'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return response()->json(['token_absent'], $e->getStatusCode());
    }

    $userId = $user->id;

    # code...
}

Upvotes: 7

Related Questions