Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.



This post first appeared on Neutron Dev, please read the originial post: here

Share the post

Set Custom Headers to HTTP Responses in Laravel

×

Subscribe to Neutron Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×