How do you add headers to a response with a middleware?

it works too, just add to middlware:


    public function handle($request, Closure $next)
{
    $request->headers->set('accept', 'application/json', true);

    return $next($request);
}


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.


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 
});