Laravel CORS Middleware

Abdou Mjr
Abdou Mjr
May 18 · 2 min read

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
<?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;}}
‘cors’ => \App\Http\Middleware\CORS::class,
Route::group([‘prefix’ => ‘auth’, ‘middleware’ => ‘cors’], function() {Route::post(‘/login’, ‘AuthController@login’);Route::post(‘/register’, ‘AuthController@register’);});

Abdou Mjr

Written by

Abdou Mjr

Web developer.