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'];
}
}
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?