Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance consideration when only user id is needed #2220

Open
mouhong opened this issue May 3, 2023 · 0 comments
Open

Performance consideration when only user id is needed #2220

mouhong opened this issue May 3, 2023 · 0 comments

Comments

@mouhong
Copy link

mouhong commented May 3, 2023

Performance consideration when only user id is needed

Sometimes we just need to use auth('api')->id() to retrieve the login user's id only. However, the id() function provided by Laravel's GuardHelper simply delegates call to user() and then returns the user's id:

public function id()
{
    if ($this->user()) {
        return $this->user()->getAuthIdentifier();
    }
}

Which means it'll always trigger a db call to retrieve the full user info even if only the id is needed.

public function user()
{
    if ($this->user !== null) {
        return $this->user;
    }

    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        // Here it'll trigger a db call if the JWT token is valid (say we are using Eloquent provider)
        return $this->user = $this->provider->retrieveById($payload['sub']);
    }
}

Suggestion

If our JWTGuard provides a customized id() function, for example:

public function id()
{
    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        return $payload['sub'];
    }
}

Then we can eliminate the unnecessary db call.

What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant