Laravel ETag and Conditionals is a package that provides a set of middleware for ETags and HTTP conditional requests.

The goal of this package is to provide tools for better client-side caching for Laravel apps.

Currently both If-None-Matched and If-Match are supported.

When using the package and enabling the middleware, your client (browser ) will take care of handling the caching provided by the ETag and If-None-Match headers automatically.

⚡ Installation

$ composer require werk365/etagconditionals

✍ Usage

You can either use the middleware group, automatically applying all available middleware (recommended if using an apiResource route for example), by setting the etag middleware, or apply the middlewares individually.

Currently available middleware:

  • setEtag
  • ifMatch
  • ifNoneMatch

ETag Support

At the heart of this package, the setEtag middleware will set the ETag header on responses.T he ETag header is equal to an md5 hash of $response->getContent()HEAD requests are supported by transforming the request to a GET request and change it back on the response.

HTTP Conditional Requests

Currently both If-None-Matched and If-Match are supported. To give a high-level understanding of how this can be useful to your app when the If-None-Match the header in the request matches the Etag, then a 304 the response is returned, and the browser will use cached content instead.
If the If-None-Match the header doesn’t match the newly created ETag value, then a 200 the response is returned. This applies to GET and HEAD requests only.

Learn more about Laravel ETag and Conditionals
Source Code

The author of the package also wrote an article that explains how to write the middleware in this package: Caching your Laravel API with ETag and Conditional Requests.