How to enable cors in laravel?

Member

by dana , in category: PHP Frameworks , 3 months ago

How to enable cors in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 3 months ago

@dana 

To enable CORS in Laravel, you can use the barryvdh/laravel-cors package. Here's how you can do it:

  1. Install the package using composer:
1
composer require barryvdh/laravel-cors


  1. Add the CorsServiceProvider to your config/app.php file:
1
2
3
4
5
'providers' => [
    ...
    BarryvdhCorsServiceProvider::class,
    ...
]


  1. Publish the configuration file:
1
php artisan vendor:publish --provider="BarryvdhCorsServiceProvider"


This will create a new cors.php configuration file in your config directory.

  1. Update the config/cors.php file with your desired configurations:
1
2
3
4
5
6
7
8
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'X-Requested-With'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,


You can customize these settings based on your specific requirements.

  1. That's it! CORS is now enabled in your Laravel application. You can further customize the CORS settings as needed by referring to the official documentation of the package: https://github.com/barryvdh/laravel-cors