Laravel Cors
Laravel Cors stats
- Downloads
- 87.7M
- Stars
- 6,260
- Open Issues
- 37
- Forks
- 625
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
CORS Middleware for Laravel by Fruitcake
The fruitcake/laravel-cors package provides an easy solution to handle CORS (Cross-Origin Resource Sharing) issues in Laravel applications. This middleware package allows developers to send CORS headers easily and manage CORS configurations effectively.
Key Features
- Automatic Handling of CORS Headers: Add CORS headers automatically to the Laravel responses, including pre-flight OPTIONS requests.
- Configurable Paths and Headers: Define specific routes (
paths) and customize allowed methods, headers, and origins through the configuration. - Support for Lumen: Includes support for integration with Lumen, the lighter Laravel framework.
Deprecated Note
As of Laravel 9.2 and above, Laravel includes CORS middleware by default. Users of Laravel 9, 10, or higher should migrate to the built-in middleware by removing the fruitcake/laravel-cors package and updating their middleware references.
Installation and Setup
-
Install via Composer:
composer require fruitcake/laravel-cors -
Register Middleware: Add
Fruitcake\Cors\HandleCors::classto the$middlewarearray inapp/Http/Kernel.php. -
Publish Configuration:
php artisan vendor:publish --tag="cors"Update the
cors.phpin the config directory to manage settings such aspaths,allowed_methods,allowed_origins, etc.
Configuration Options
- Paths: Specify routes to apply CORS, e.g.,
['api/*']. - Allowed Methods: HTTP methods allowed, e.g.,
['POST', 'GET']or['*']for all. - Allowed Origins: Specify which origins can access the resources, e.g.,
['http://example.com']. - Supports Credentials: Boolean to specify if cookies and authorization headers should be supported.
Usage in Lumen
For Lumen, manually register Fruitcake\Cors\CorsServiceProvider::class in bootstrap/app.php and configure as needed.
Common Issues
- Configuration Mistakes: Ensure correct paths are set in
cors.php. Use detailed errors to debug issues. - Middleware Order: CORS Middleware should be the first in the global middleware stack to ensure headers are always set.
- Duplicate Headers: Ensure CORS headers are only set in one place to avoid conflicts.
Conclusion
The fruitcake/laravel-cors package is essential for Laravel developers needing to manage CORS in their applications. With its deprecation in Laravel 9.2 and newer versions due to built-in support, developers should plan migration accordingly. For applications on earlier versions or for Lumen, fruitcake/laravel-cors remains a robust choice, providing comprehensive options for CORS management.
License
This package is open-sourced software licensed under the MIT license.