Skip to content
Advertisement

Laravel 8 custom headers run only for home page

I want to add custom headers for every response from my Laravel project.

I created a middleware using php artisan make:middleware customheaders then I used this code in customheaders middleware

public function handle(Request $request, Closure $next)
{
    $response = $next($request);
    $response->header('X-CUSTOM-HEADER', 'myCustomHeader');
    return $response;
}

then I added my class to kernel

    protected $middleware = [
        ...
        AppHttpMiddlewarecustomheaders::class,
    ];

Now if I run my application home page localhost:8000 I can see my custom headers but if I go to any other page like localhost:8000/dashboard I can’t see my custom headers.

There are no any errors that appears, also no errors on the logs.

So what’s wrong?

Advertisement

Answer

After a lot of searching I can’t figure a way to do it with Laravel.
I tried to add my custom middleware to global middlewares.
Also tried to pass each route through the middleware.
But always the same result, The headers are showen only at home page only.

So I did it by the old way I edited public/index.php file and added header() at the top of the file and it worked perfectly.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement