Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 470
Marwelln Avatar asked Feb 10 '15 09:02

Marwelln


1 Answers

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 
});
like image 52
Syed Waqas Bukhary Avatar answered Sep 22 '22 17:09

Syed Waqas Bukhary