Laravel CORS Middleware

Abdelkader MOUDJAR
2 min readMay 18, 2019

--

What is CORS?

CORS stands for Cross-origin resource sharing. The concept is related to the same origin policy which all browsers implement. In a nutshell, this policy says that a web site may not perform web requests to a different web site, or to be precise, “origin” (scheme, hostname, port number). CORS is a mechanism that can relax such restrictions. While the browser enforces restriction, CORS must be implemented on the server side to let the browser know that it may relax the restrictions.

Let’s get started

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

php artisan make:middleware corsMiddleware

That command will create a middleware file in /app/Http/Middleware, now open the new file in editor and add the following code

<?phpnamespace App\Http\Middleware;use Closure;class corsMiddleware{/*** @param $request* @param Closure $next* @return mixed*/public function handle($request, Closure $next) {$response = $next($request);$response->headers->set('Access-Control-Allow-Origin' , '*');$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application','ip');return $response;}}

Now go to /app/Http/Kernel.php, add the following line to the $middleware array:

\App\Http\Middleware\corsMiddleware::class

After that add the bellow line to the $routeMiddleware array inside the same directory /app/Http/Kernel.php

‘cors’ => \App\Http\Middleware\CORS::class,

And that’s it, now the corsMiddleware is ready to use, here is an example how to use it in your routes :

Route::group([‘prefix’ => ‘auth’, ‘middleware’ => ‘cors’], function() {Route::post(‘/login’, ‘AuthController@login’);Route::post(‘/register’, ‘AuthController@register’);});

--

--