DEV Community

AquaCat
AquaCat

Posted on

【Laravel】How to allow cross-origin in Laravel

*Laravel version...8.75

What is cross-origin

"Origin" a combination of "scheme", "hostname" and "port."
If a request is from the same origin as the web server, the server enables web clients to access to it (process their requests). If not, the web server reject the access from them.

How to allow cross-origin in Laravel

1.Install "fruitcake/laravel-cors"

composer require fruitcake/laravel-cors
Enter fullscreen mode Exit fullscreen mode

2.Add "laravel-cors" to the global middleware.

//app/Http/Kernel.php
 protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,//<---add
Enter fullscreen mode Exit fullscreen mode

3.Create a file to set CORS.

php artisan vendor:publish --tag="cors"
Enter fullscreen mode Exit fullscreen mode

4.Set "allowed_origins_patterns" to "[]" in cors config.

//config>cors.php
<?php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
     //↓Added
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];
Enter fullscreen mode Exit fullscreen mode

5.Then your Laravel server allows CORS!!

Top comments (0)