Enabling CORS in Laravel 5.x

If you have built your RESTful api using laravel chances are your fontend developers will face problems talking to your api with javascript. They might see errors in your Dev tool console like the following

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com. This can be fixed by moving the resource to the same domain or enabling CORS.

The way you can fix this is by introducing a CORS middleware in your laravel app and register it. Its simple than you can even think of.

Step 1

Lets create a new middleware and name it Cors

A file will be created at app\Http\Middleware

Step 2

Open the newly create file Cors.php from the above path and replace the content of the handle() method with the following

Step 3

Open app\Http\Kernal.php and register your Cors middleware by adding the following code in the $middleware array.

 

Step 4

No step 4. You should be all set.