Menü schliessen
Created: September 11th 2024
Categories: Laravel,  Php
Author: Miljan Puzovic

Control Browser Caching in Laravel

Tags:  guide,  Laravel,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Caching is a vital aspect of web development that impacts the performance and behavior of your application. While caching can drastically improve loading times by storing resources, there are scenarios where you may want to prevent caching altogether. For example, when dealing with dynamic or sensitive content, it's crucial to ensure that users always receive the most up-to-date information without any data being stored in their browsers. This is where custom cache control middleware comes into play.

First we are going to create a BrowserCache.php file using command
php artisan make:middleware BrowserCacheNow we can completely replace the content of that file with this code


<?php
namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BrowserCache
{
    /**
    * Handle an incoming request.
    *
    * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
    */
    public function handle(Request$request, Closure$next): Response
    {
       // Pass the request to the next middleware or controller and capture the response
       $response=$next($request);
       // Set Cache-Control header to prevent any kind of caching
       $response->headers->set(
           'Cache-Control',
           'no-store, no-cache, max-age=0, must-revalidate, private'
       );
       // Set Expires header to the current timestamp to indicate the resource has already expired
       $response->headers->set(
           'Expires',
           Carbon::now()->format('D, d M Y H:i:s T')
       );
       return$response;
   }
}

The rest of the code should be clear, so let's focus on handle() method:

  • Request Passing: The request is first passed through the next layer in the middleware stack or directly to the controller using $next($request). This method ensures that any prior middleware in the stack has had a chance to process the request.
  • Cache-Control Header: The Cache-Control header is set with multiple directives:
    • no-store: This prevents the browser from storing any part of the response.
    • no-cache: Ensures that the browser always validates the freshness of a resource with the server before using the cached version.
    • max-age=0: The resource is considered stale immediately.
    • must-revalidate: The browser must check with the server before using the cached resource.
    • private: The response is meant for a single user and should not be stored by shared caches (e.g., proxies).
  • Expires Header: The Expires header is set to the current timestamp using Carbon, effectively marking the response as expired the moment it is generated.

Of course, in addition we need to ensure that this middleware is registered correctly by adding it to Kernel.php

protected $routeMiddleware = [
    // Other middlewares...
    'browserCache' => \App\Http\Middleware\BrowserCache::class,
];

After that we can use browserCache Middleware on our routes.