I can't figure out how to how to add headers to a response from a middleware. I've used both ->header(...)
and ->headers->set(...)
but both gives errors. So how do you do it?
First I tried with
public function handle($request, Closure $next) {
$response = $next($request);
$response->headers->set('refresh', '5;url=' . route('foo'));
return $response;
}
which is the same as in Illuminate\Http\Middleware\FrameGuard.php
, but that gives
Call to a member function set() on a non-object
Second I tried with
public function handle($request, Closure $next) {
$response = $next($request);
$response->header('refresh', '5;url=' . route('foo'));
return $response;
}
But that gives
Method [header] does not exist on view.
So how do you add headers from a middleware?
I solved this by using the response
helper.
use Illuminate\Http\RedirectResponse;
$response = $next($request);
$response = $response instanceof RedirectResponse ? $response : response($response);
return $response->header('refresh', '5;url=' . route('foo'));
All my other middleware seems to run fine with this so I guess it's fine.