You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Why the Database Queries Happen

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 default TokenGuard goes a step further: it pulls the corresponding oauth_access_tokens record 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 associated User model 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 your User model has any relationships set to auto-load (via the $with property) or if your app logic pulls in user-related data elsewhere in middleware or controllers, those can add even more database hits.

How to Cut Down on Queries

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:45