DEV Community

AquaCat
AquaCat

Posted on

1 1

【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!!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay