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?
Here is a solution tested in Laravel 5.0 to attach headers to routes
Create a middleware file app/Http/Middleware/API.php
<?php namespace App\Http\Middleware;
use Closure;
class API {
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, X-Auth-Token');
$response->header('Access-Control-Allow-Origin', '*');
//add more headers here
return $response;
}
}
Add middlewear to kernel file by adding these lines to /app/Http/Kernel.php
protected $middleware = [
//... some middleware here already
'\App\Http\Middleware\API',// <<< add this line if you wish to apply globally
];
protected $routeMiddleware = [
//... some routeMiddleware here already
'api' => '\App\Http\Middleware\API', // <<< add this line if you wish to apply to your application only
];
Group your routes in the routes file /app/Http/routes.php
Route::group(['middleware' => 'api'], function () {
Route::get('api', 'ApiController@index');
//other routes
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With