Easiest Way to Allow CORS in Laravel 6 or Any Version

In this tutorial, I’m going to share how to allow Cross-Origin Resource Sharing (CORS) in Laravel 6 or any version of Laravel.

According to Wikipedia: Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

We can allow CORS in many ways in Laravel. Let’s solve the issue by following the easiest way.

The Easiest Solution

Go to bootstrap folder and open app.php file. Then just add these lines at the top of the file.

app.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

Another Solution

Run this artisan command:

php artisan make:middleware Cors

Now open Cors.php from App\Http\Middleware folder and replace handle() function with this code:

Cors.php
public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorizations');
}

Lastly, open Kernel.php from App\Http folder add the below line to the $middleware array:

protected $middleware = [
    ...
    \App\Http\Middleware\Cors::class,
];

Now run the application and call API from anywhere.

The tutorial is over. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.