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

EverdevFR's avatar

Laravel Sanctum and error 406

Good morning,

For my API, I use Laravel 11 with Sanctum for token management. I would like to know how to modify the Laravel return http code when a token is not valid? (Today I have a 406 code and I would like to have a 401 code).

My "token" table was renamed to t_token_tok and I added this code in AppServiceProvider:

    public function boot(): void
    {
        Sanctum::usePersonalAccessTokenModel(Token::class);

        Sanctum::authenticateAccessTokensUsing(
            static function (PersonalAccessToken $accessToken, bool $is_valid) {
                if (!$is_valid && $accessToken->expires_at && $accessToken->expires_at->isPast()) {
                    return false;
                } else {

                    /* On actualise l'heure d'expiration du token si la dernière requete était bonne */
                    $accessToken->expires_at = now()->addMinute(30);
                    $accessToken->save();

                    return true;
                }
            }
        );
    }
0 likes
0 replies

Please or to participate in this conversation.