Cross-Origin Resource Sharing (CORS) with Laravel 5

Introduction

If you are working or have worked with APIs then you have definitely heard about CORS at least once. If not, Cross-Origin Resource Sharing (CORS) is a brand new standard introduced by HTML5. CORS permits web applications to define which origins (website or domains) are allowed to gain access to the specific resources on the server.

An example of cross-origin request  can be:

Let’s say corsexample.com wants to access data from laravel-nepal.com .

For security reasons ,these type of request wouldn’t be allowed under the browser’s same origin policy which says that a web application using those APIs can only request HTTP resources from the same domain the application was loaded from unless CORS headers are used. – https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

laravel-nepal.com can use few response headers that allows corsexample.com to access data.

How do I enable CORS in laravel 5.5?

When we are sending out ajax request or any other frontend framework like vue/angular request, we might face errors like

To handle this problem, first let’s create our own CORS middleware :

  • Run the following command in your terminal.

php artisan make:middleware Cors

  • Go to the middleware in app/Http/Middleware/Cors.php  and inside the handle()  function add the following

In this middleware, we are adding additional headers to the incoming requests. The first header ‘Access-Control-Allow-Origin’ allows all the origin ( website or domains ). Well, you can use your own list of specific websites there. The second header ‘Access-Control-Allow-Methods’, for the sake of simplicity we have added all the methods available instead of * so that you can customize it as per your requirement. The last header ‘Access-Control-Allow-Headers’ adds different types of headers to be allowed.

Next we need to register this middleware in app/http/kernel.php.

Now we can finally use it like :

There are many options out there, like, we can use Laravel package https://github.com/barryvdh/laravel-cors or we can create our own custom one. Happy coding 🙂

Sharing is caring!

Related Post