Laravel Passport的auth:api中间件为何多次请求数据库?
Hey there, great question! It’s totally reasonable to wonder why Passport hits the database multiple times with the auth:api middleware, even though it’s built on JWT. Let me break down exactly what’s going on:
Passport uses JWT under the hood, but its default auth:api setup isn’t purely stateless. Here are the key reasons for those extra database calls:
Token revocation checks
JWT handles signature verification and expiration out of the box without touching the database. But Passport’s defaultTokenGuardgoes a step further: it pulls the correspondingoauth_access_tokensrecord from the database to make sure the token hasn’t been manually revoked (even if the JWT’s expiration date hasn’t passed). This lets you invalidate tokens instantly if needed—like when a user logs out or their permissions change.Loading the authenticated user
Once the token is validated, the guard automatically fetches the associatedUsermodel so you can access$request->user()in your controllers. That’s another database query right there, unless you’ve set up caching or eager loading for user data.Optional: Relationship-related queries
If yourUsermodel has any relationships set to auto-load (via the$withproperty) or if your app logic pulls in user-related data elsewhere in middleware or controllers, those can add even more database hits.
If you don’t need to support manual token revocation and want a fully stateless flow, you can enable Passport’s stateless mode:
// In your AuthServiceProvider's boot method Passport::routes(); // Add this line to skip database checks Passport::stateless();
This tells Passport to rely solely on the JWT’s signature and expiration claims, skipping the oauth_access_tokens lookup entirely. Just keep in mind that you won’t be able to revoke tokens manually anymore once you enable this.
Alternatively, you can use Laravel’s caching system to store user and token data, which will prevent repeated database calls for the same user/token on subsequent requests.
内容的提问来源于stack exchange,提问作者Vajiheh Habibi

