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

raphael's avatar

Set custom header for any response

I would like to set a header like "Cache-Control: no-cache, must-revalidate" for any view response in my application.

Currently, I'm returning view responses from Controllers like this: return view('users.index'); Using this, the Cache-Control header says "no-cache".

In the documentation I found how to define Response Macros which can be re-used for many responses. (http://laravel.com/docs/5.1/responses#response-macros)

But I want to add the header to any view()-call.

How can I make this work in an easy way?

0 likes
5 replies
pmall's avatar

Why you want to send this for every views ? Why only views ?

But you can achieve this with response macro :

public function boot(ResponseFactory $factory)
{
    $factory->macro('nocache', function ($view_name, view_data = []) use ($factory) {

        $content = view($view_name, $view_data);

        return response($content)->header('Cache-Control', 'no-cache, must-revalidate');

    });
}

Then use response()->nocache('view.name', ['foo' => $bar]) everywhere instead of view('view.name', ['foo' => $bar]).

raphael's avatar

Looks promising. Where would I paste that code in?

phildawson's avatar
Level 26
  1. create the file \App\Http\Middleware\NoCache.php
<?php

namespace App\Http\Middleware;

use Closure;

class NoCache
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Cache-Control', 'no-cache, must-revalidate');

        return $response;
    }
}
  1. Open \App\Http\Kernel.php and add to $middleware if you want it on all
 \App\Http\Middleware\NoCache::class,

or define the key to pick and choose.

'nocache' => \App\Http\Middleware\NoCache::class,

Done.

2 likes
pmall's avatar

The middleware will put this for all responses not only views.

Again I'm curious to know why you want to do this. Maybe you're missing something.

phildawson's avatar

@raphael as @pmall has mentioned this is all responses.

If you wanted to say narrow it down to just responses formed from views then you'll need to obviously check before slapping the header on everything.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\View\View;

class NoCache
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($response instanceof Response and $response->getOriginalContent() instanceof View)
        {
           $response->header('Cache-Control', 'no-cache, must-revalidate');
        }

        return $response;
    }
}
1 like

Please or to participate in this conversation.