How to Enable Cors with Laravel 5

By default, cors requests are not enabled with any PHP farameworks. You should enable it if you need to use cors request.

Even, you can enable cors request, i strongly suggest you yo use a proxy server. Accept requests from your proxy server,  pass it to your application server, don’t let any other client make any http request from your application server.

Here is how to enable CORS with Laravel 5 PHP framework:

1. Create CORS Middleware

To initialize middleware class you should use artisan command line tool.

This command will create the Cors.php file at /app/Http/Middleware

You should edit, Cors.php file

2. Register Middleware

To use your middleware in your project you should register middleware class into your project. To register your middleware you should edit /app/Http/Kernel.php file.

In the end of the file you should see $routeMiddleware array. That is object we should add our middleware. We will update routeMiddleware like this:

We game ‘cors’ name to our middleware. Now Laravel will load our middleware but won’t use it until we put it in routes.

3. Make Your Routes Use CORS Middleware

You have options when you want to make your routes use your middleware.  I usually prefer to create route groups that uses same middleware. But sometimes you need to use Route::get()->middleware([middlewares]) That is the way how you can assign middleware to only one route.

Here is my favourite way to call middleware:


4. Done!

You’ve done for today.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.