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

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

<?php

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() {

Abdou Mjr

Written by

Abdou Mjr

Web developer.