Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dukesteen's avatar

[Sanctum] two flavours of api key

Hi, I am brainstorming about the best way to handle 2 types of api keys using Laravel Sanctum. One type of api key would be bound to a tenant, and the other type of api key would be bound to an individual user. Would this require me to have two Authenticatable models?

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

class ApiKey extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
0 likes
6 replies
dukesteen's avatar

@pkboom Yes, I know that, but can I have one type of api key that automatically expires and one that doesn't?

pkboom's avatar

@dukesteen sorry for being late. When you create a token, you can set expires_at. So if you set it, the token has an expiration. If you don't, then it doens't expire until you revoke it. Below is the source code of Sanctum.

public function createToken(string $name, array $abilities = ['*'], DateTimeInterface $expiresAt = null)
    {
        $token = $this->tokens()->create([
            'name' => $name,
            'token' => hash('sha256', $plainTextToken = Str::random(40)),
            'abilities' => $abilities,
            'expires_at' => $expiresAt,
        ]);

        return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
dukesteen's avatar

@pkboom From what I know there isn't an expires_at property on the default personal access token model? Would I need to override the createToken function on the user model class that implements HasApiTokens?

pkboom's avatar

@dukesteen Why don't you take a look at the code HasApiTokens.php > createToken()? It sure has $expiresAt as a parameter.

dukesteen's avatar

@pkboom Ah, I am still on laravel 8 and sanctum 2.15. In this version the expires_at property is not available by default.

Please or to participate in this conversation.