Adding Custom Header with Response in Laravel

I was working out for the best way to add some custom header to my application for most of the view responses, I wanted the header to be "Cache-Control: no-cache, must-revalidate".

I came up with the best solution with a laravel middleware and decided to share the code snippets with the laravel community people as well. The code snippet will give an idea for you to work on next similar logic and the great solution for setting up the custom header.

Let's get started ;)

Create new middleware with an artisan command, it will be stored in \App\Http\Middleware\NoCache.php

php artisan make:middleware NoCache

<?php

namespace App\Http\Middleware;

use Closure;

/**
 * Class NoCache
 * @package App\Http\Middleware
 */
class NoCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Cache-Control', 'no-cache, must-revalidate');

        return $response;
    }
}

Open \App\Http\Kernel.php and register the middleware.

There are different ways you might want to use this middleware, you could either apply it globally on every HTTP request over the application or use only on specific routes.

 

a. Register like below to apply globally on every HTTP request.

    /**
     * @var array
     */
    protected $middleware = [
        ...
        \App\Http\Middleware\NoCache::class,
    ];

b. Another way is, registering with a key and apply it on routes with that key like below.

    /**
     * @var array
     */
    protected $routeMiddleware = [
        ...
        'nocache' => \App\Http\Middleware\NoCache::class,
    ];

Now, applying middleware on routes.

Route::group(['middleware' => 'nocache'], function () {
    Route::get('blog/{slug}', [
        'as' => 'app.blog.view',
        'uses' => 'BlogController@view',
    ]);
});

We are done!

Conclusion

Thanks for reading this post up to the end, if you think this post is worth reading, feel free to share with others, also if you have feedback please post in the comment section below.

Happy Coding!