John Mellor
John Mellor

Reputation: 2513

Laravel redirect with no cache header

I'm using Laravel 3 and it's not obvious how to set headers in any way other than through Response::make().

I am doing a redirect like this:

return Redirect::to('admin/check');

I'd like to set an additional no-cache header for the redirect like so:

"Cache-Control: no-store, no-cache, must-revalidate"

I realize I could just do this directly in PHP, but is there any way to set response headers via Laravel?

Upvotes: 2

Views: 8387

Answers (2)

sepehr
sepehr

Reputation: 18505

I'm afraid, the accepted answer is wrong and misleading!

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.

You might be thinking that this code should work just fine:

return Redirect::to('admin/check')
    ->header('Cache-Control', 'no-store, no-cache, must-revalidate');

But it won't. You're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object. And it needs CORS implemented on the target server to allow such ajax requests.

Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.

That's not how the web works.

Upvotes: 3

vFragosop
vFragosop

Reputation: 5773

When you call Redirect::to() Laravel instantiates a Response object with 302 status and a Location header. That Response object is then returned by the controller and rendered as a proper HTTP response, so, at controller time, you can still change its headers.

To be even more precise class Redirect extends Response. Take a look here You can achieve that by simply using:

return Redirect::to('admin/check')
    ->header('Cache-Control', 'no-store, no-cache, must-revalidate');

Upvotes: 5

Related Questions