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

pilat's avatar
Level 41

Caching responses on specific URLs

Hi, is there a way to cache JSON responses on selected routes/URLs?

Say, /api/account/some-id — return it from cache unless it is 5+ minutes old.

Preferably, if the cached resource can be returned without even hitting PHP.

Even more preferably, if I could setup this via .htaccess =)))

0 likes
1 reply
bobbybouwmann's avatar

In Laravel you can simply do this in your controller or using a middleware. You can for example make a config file and list all routes you want to cache. Whenever a routes hit you have a middleware that will check if there is a cached version and server that response, if not let it serve the original backend way. For caching the route you can use another middleware. It's called termination middleware, basically a middleware action that is performed on the full response. This way you can store it in the cache.

So I think a middleware is the way to go here ;)

On server level you have a lot of tools for that. The one I prefer is varnish. This runs just before your server so it should be able to return a cached version.

1 like

Please or to participate in this conversation.