Search code examples
laravellaravel-passport

Laravel passport createToken without User model


Normally, I can create the token as following:

$user = User::find( $tokenData['user_id'] );
return $user->createToken($tokenData['name'])->accessToken;

Since I have access to the user_id, is it possible to create a token without creating one more query (User::find)?

Because theoretically the token itself has nothing to do with the user object, but user_id (which I have it in tokenData array).


Solution

  • This is the createToken method from the HasApiTokens trait:

    public function createToken($name, array $scopes = [])
    {
        return Container::getInstance()->make(PersonalAccessTokenFactory::class)->make(
            $this->getKey(), $name, $scopes
        );
    }
    

    Based on this, it seems like you could change your code to:

    return app(\Laravel\Passport\PersonalAccessTokenFactory::class)->make($tokenData['user_id'], $tokenData['name'])->accessToken;
    

    That being said, it would probably be better just to make the one extra query. You'd be making your code harder to read, understand, and maintain, in order to save maybe 1 millisecond. The trade-off doesn't seem worth it.