How to handle CORS in Laravel 5

CORS stands for Cross-Origin Resource Sharing. Origin policy allows only the same origins to share data and this policy will prevent Cross-site Request Forgery attacks. So to enable sharing resources between different origins we use CORS mechanism by setting a special header. By adding a specific origin in the header, you are allowing only those origins to load resources from the API server.

When you try to make an XHR request to API server. If you will get the following message in your browser’s console, it means that you need to enable CORS between the origins.
"XMLHttpRequest cannot load NO 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost/' is therefore not allowed access. The response had HTTP status code 500."

Here I am going to show you handling CORS in Laravel 5. You can use this technique on any other framework.

By setting header('Access-Control-Allow-Origin: *'); header in the API responses you can allow any origin to access the resources API. But it is not recommended as it is not secure.

There is another header called Access-Control-Allow-Methods basically by using this header we can limit the communication methods. for example following header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); header will only allow mentioned methods.

In order to apply this technique in laravel 5, we are going to use Middlewares. So let’s create a middleware called “Cors”.

Using your Terminal or command prompt, navigate to your project’s root directory and run the following artisan command:

Above command will create a middleware file in /app/Http/Middleware, using your editor open the file and add below code in it.

Now go to /app/Http/Kernel.php and update it by adding the following 'cors' => \App\Http\Middleware\Cors::class,. which will make Laravel aware of your custom middleware:

That is it. Our custom CORS middleware is ready to use. You can use this middleware just like other middlewares.

You can also use with Route groups –

If you want to allow api access to a specific domain, instead of “*” you can use domain name:

On Apache, you can do this in an httpd.conf section or .htaccess file using mod_headers and this syntax:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.


Leave a Reply

Your email address will not be published.