There are a lot of useful middlewares already registered inside Laravel, like the authentication mechanisms, authorization, a throttler, and even the one responsible to make route model binding possible. Practically, your middleware needs are covered. Except for one.

There is one middleware that doesn’t get the spotlight in Laravel. It’s called SetCacheHeaders , which is aliased as cache.headers . And, there is no mention of it in the documentation. I’m not joking, guys:

Who, when, how?

A quick look around in the api documentation and the source repository says this middleware was added added before christmas of 2017 after a lengthy discussion, but it's a mystery why nobody has talked about it since it’s seems very… convenient. In any case, after making this article, my PR to the documentation was accepted, so you should find it now in the documentation.

A simple glance on the middleware tell us that we can use it to add cache headers into the Response, saving us the work to create our own middleware.

Cache in the Response? What do you mean?

If you are asking that, it means you don’t know what is the HTTP Cache Control directive.

In a nutshell, the Cache Control is a way to tell the browser if the response your application sent should be cached, and under what conditions, so it can decide if it should receive again a full response or not.

This is a very browser-centric mechanism, you will see later why. There is a very good article in Google Developers that it will teach how it works that you definitely should read. I will wait.

Ready? Now that we know how the HTTP Cache Control works, we can understand what this middleware tries to achieve. Or skip the next section for the useful part.

How the SetCacheHeaders middleware works?

Let’s check the source code.

As you can see, there are five main statements inside the handle() method in this middleware. Trying to verbalize what each does:

It starts with checking if the request is GET or HEAD . You can’t cache a POST response, since this method means changed things. Checks if you passed any parameter to the middleware, and parses them into the Response headers using the handy parseOptions() method. If the etag option has been set, it will automatically hash the response content so it can be quickly compared against the etag the Request sent. It will set the Cache-Control options inside the Response headers. And finally, it will check if the response has not been modified. If it wasn’t, it will remove the content and only return the etag , saving precious kilobytes.