laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.
- Handles CORS pre-flight OPTIONS requests
- Adds CORS headers to your responses
- Match routes to only add CORS to certain Requests
fruitcake/laravel-cors package in your
composer.json and update your dependencies:
composer require fruitcake/laravel-cors
If you get a conflict, this could be because an older version of barryvdh/laravel-cors or fruitcake/laravel-cors is installed. Remove the conflicting package first, then try install again:
composer remove barryvdh/laravel-cors fruitcake/laravel-cors composer require fruitcake/laravel-cors
To allow CORS for all your routes, add the
HandleCors middleware at the top of the
$middleware property of
protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... ];
Now update the config to define the paths you want to run the CORS service on, (see Configuration below):
'paths' => ['api/*'],
The defaults are set in
config/cors.php. Publish the config to copy the file to your own config:
php artisan vendor:publish --tag="cors"
Note: When using custom headers, like
X-Requested-With, you must set the
allowed_headersto include those headers. You can also set it to
['*']to allow all custom headers.
Note: If you are explicitly whitelisting headers, you must include
Originor requests will fail to be recognized as CORS.