Could we help you? Please click the banners. We are young and desperately need the money
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 BrowserCache
Now 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:
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.