Set Custom Headers to HTTP Responses in Laravel

Let’s look at how we can add custom headers to HTTP responses in a Laravel application.

 

Create a Middleware

One good solution, in this case, is to create a Middleware.

Run the following command:

php artisan make:middleware NeutronHeaders

Don’t forget to choose a proper name for the Middleware.

The namespace will be \App\Http\Middleware\NeutronHeaders.php

Let’s create a custom header but let’s also change an existing one like Cache-Control, to show you how it works.

Now there are different ways we may use this Middleware.

We can apply it globally on every HTTP request or we can use it only on specific routes.

We’ll go over both but let’s first apply it globally.

Let’s open the \App\Http\Kernel.php file.


Add Custom Headers to All HTTP Requests

Inside the protected $middleware array, register the Middleware.

Call any API inside the project and notice that the custom headers are now globally set.

Add Custom Headers to Specific Routes

Remove the Middleware from the $middleware array and register it inside the $routeMiddleware array in \App\Http\Kernel.php.

Then go to the file where you have defined your routes. Typically is the routes/api.php file.

Then apply the Middleware to the routes you desire.

You should now be all set!


Let me know what you think about this article through comments below, or on Twitter at @pelu_carol.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.

 

You may also like...