You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
publicfunctionid()
{
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.
publicfunctionuser()
{
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:
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, theid()
function provided by Laravel's GuardHelper simply delegates call touser()
and then returns the user's id:Which means it'll always trigger a db call to retrieve the full user info even if only the id is needed.
Suggestion
If our
JWTGuard
provides a customizedid()
function, for example:Then we can eliminate the unnecessary db call.
What do you think?
The text was updated successfully, but these errors were encountered: