Allow CORS in Laravel

When you have local development with some other applications trying to connect to your Laravel backend, you will notice errors CORS error on console. That means, you would need to setup CORS to be enabled for backend routes.

We achieve that by creating middleware,

$ php artisan make:middleware Cors

Update the header returned in app/Http/Middleware/Cors.php

namespace App\Http\Middleware;
use Closure;
class Cors
public function handle($request, Closure $next)
return $next($request)
->header(‘Access-Control-Allow-Origin’, ‘*’)
->header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’)
->header(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type, X-Token-Auth, Authorization’);

You should update the appropriate value in returning headers.

Then, register in app/Http/kernel.php

protected $routeMiddleware = [
‘auth’ => \App\Http\Middleware\Authenticate::class,
‘auth.basic’ => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
‘guest’ => \App\Http\Middleware\RedirectIfAuthenticated::class,
‘cors’ => \App\Http\Middleware\Cors::class, // <-- add this line

Finally, any route that you want to enable CORS, just add this middleware on route registration.

Have fun :)