laravel-cors
Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
Top Related Projects
Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
Cross-origin resource sharing library and stack middleware.
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
Quick Overview
fruitcake/laravel-cors is a Laravel package that adds CORS (Cross-Origin Resource Sharing) support to your Laravel application. It provides a middleware to handle CORS preflight requests and adds the necessary headers to your responses, allowing you to easily configure and manage cross-origin requests in your Laravel projects.
Pros
- Easy integration with Laravel applications
- Highly configurable with a wide range of options
- Supports both global and route-specific CORS settings
- Actively maintained and compatible with recent Laravel versions
Cons
- May require additional configuration for complex CORS scenarios
- Could potentially impact performance if not optimized for high-traffic applications
- Limited to Laravel framework, not suitable for other PHP projects
Code Examples
- Basic CORS configuration in
config/cors.php
:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
- Adding CORS middleware to specific routes:
use Fruitcake\Cors\HandleCors;
Route::group(['middleware' => [HandleCors::class]], function () {
Route::get('/api/data', 'ApiController@getData');
});
- Customizing CORS for a specific route:
use Fruitcake\Cors\HandleCors;
Route::get('/api/special', [
'middleware' => [
HandleCors::class => [
'allowed_origins' => ['https://example.com'],
'allowed_methods' => ['GET', 'POST'],
],
],
'uses' => 'ApiController@getSpecialData',
]);
Getting Started
-
Install the package via Composer:
composer require fruitcake/laravel-cors
-
Publish the configuration file:
php artisan vendor:publish --tag="cors"
-
Add the middleware to your
app/Http/Kernel.php
file:protected $middleware = [ // ... \Fruitcake\Cors\HandleCors::class, ];
-
Configure CORS options in
config/cors.php
as needed. -
Your application is now ready to handle CORS requests according to your configuration.
Competitor Comparisons
Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
Pros of NelmioCorsBundle
- More comprehensive configuration options for fine-tuning CORS behavior
- Better integration with Symfony framework and its ecosystem
- Supports multiple CORS configurations for different routes or domains
Cons of NelmioCorsBundle
- Slightly more complex setup and configuration process
- Limited to Symfony applications, whereas laravel-cors is more versatile
- May require more manual intervention for custom CORS scenarios
Code Comparison
NelmioCorsBundle configuration:
nelmio_cors:
defaults:
allow_origin: ['http://example.com']
allow_methods: ['GET', 'POST', 'PUT', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
laravel-cors configuration:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_headers' => ['*'],
];
Both packages provide CORS support for their respective frameworks, but NelmioCorsBundle offers more granular control at the cost of increased complexity. laravel-cors is simpler to set up and use, making it a good choice for straightforward CORS requirements in Laravel applications. NelmioCorsBundle is better suited for Symfony projects with complex CORS needs across multiple domains or routes.
Cross-origin resource sharing library and stack middleware.
Pros of stack-cors
- Framework-agnostic, can be used with any PHP project
- Lightweight and focused solely on CORS functionality
- Easier to integrate into non-Laravel applications
Cons of stack-cors
- Requires more manual configuration in Laravel projects
- Less Laravel-specific features and optimizations
- May require additional setup for Laravel middleware integration
Code Comparison
stack-cors:
$app->add(new Asm89\Stack\CorsService($options));
laravel-cors:
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
];
Key Differences
-
Integration: laravel-cors is specifically designed for Laravel, offering seamless integration, while stack-cors is more versatile but requires additional setup for Laravel projects.
-
Configuration: laravel-cors provides Laravel-specific configuration options and defaults, whereas stack-cors offers more generic configuration that may need adaptation for Laravel use.
-
Maintenance: laravel-cors is actively maintained with a focus on Laravel compatibility, while stack-cors has a broader scope but may have less frequent updates specific to Laravel.
-
Community: laravel-cors has a larger user base within the Laravel ecosystem, potentially leading to more Laravel-specific support and resources.
-
Performance: laravel-cors may have slight performance advantages in Laravel applications due to its tailored integration and optimizations.
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
Pros of laravel-mongodb
- Provides MongoDB integration for Laravel, allowing use of MongoDB as a database backend
- Offers Eloquent model support for MongoDB collections
- Includes query builder functionality tailored for MongoDB operations
Cons of laravel-mongodb
- More complex setup and configuration compared to laravel-cors
- Requires additional knowledge of MongoDB concepts and query syntax
- May have performance implications for certain types of queries compared to traditional SQL databases
Code Comparison
laravel-mongodb:
use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model
{
protected $connection = 'mongodb';
}
laravel-cors:
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_headers' => ['*'],
];
Key Differences
- Purpose: laravel-mongodb integrates MongoDB with Laravel, while laravel-cors handles Cross-Origin Resource Sharing
- Functionality: laravel-mongodb affects database operations, laravel-cors manages HTTP headers for cross-origin requests
- Scope: laravel-mongodb is a database driver, laravel-cors is a middleware for handling CORS
Use Cases
- laravel-mongodb: Projects requiring flexible schema design or handling large amounts of unstructured data
- laravel-cors: Applications needing to securely allow cross-origin requests, especially for APIs consumed by frontend applications on different domains
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
CORS Middleware for Laravel
Implements https://github.com/fruitcake/php-cors for Laravel
Note for users upgrading to Laravel 9, 10 or higher
This package is deprecated because all supported Laravel versions now include the CORS middleware in the core.
Since Laravel 9.2, this Middleware is included in laravel/framework. You can use the provided middleware, which should be compatible with the Middleware and config provided in this package. See https://github.com/laravel/laravel/pull/5825/files for the changes.
Steps to upgrade:
- Remove
"fruitcake/laravel-cors"
from your composer.json - Replace
\Fruitcake\Cors\HandleCors::class,
with\Illuminate\Http\Middleware\HandleCors::class,
inapp/Http/Kernel.php
See https://github.com/fruitcake/php-cors
for advanced usage. The config stays the same.
About
The laravel-cors
package allows you to send Cross-Origin Resource Sharing
headers with Laravel middleware configuration.
If you want to have a global overview of CORS workflow, you can browse this image.
Upgrading from 0.x (barryvdh/laravel-cors)
When upgrading from 0.x versions, there are some breaking changes:
- A new 'paths' property is used to enable/disable CORS on certain routes. This is empty by default, so fill it correctly!
- Group middleware is no longer supported, use the global middleware
- The vendor name has changed (see installation/usage)
- The casing on the props in
cors.php
has changed from camelCase to snake_case, so if you already have acors.php
file you will need to update the props in there to match the new casing.
Features
- Handles CORS pre-flight OPTIONS requests
- Adds CORS headers to your responses
- Match routes to only add CORS to certain Requests
Installation
Require the 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
Global usage
To allow CORS for all your routes, add the HandleCors
middleware at the top of the $middleware
property of app/Http/Kernel.php
class:
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/*'],
Configuration
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-Auth-Token
orX-Requested-With
, you must set theallowed_headers
to include those headers. You can also set it to['*']
to allow all custom headers.
Note: If you are explicitly whitelisting headers, you must include
Origin
or requests will fail to be recognized as CORS.
Options
Option | Description | Default value |
---|---|---|
paths | You can enable CORS for 1 or multiple paths, eg. ['api/*'] | [] |
allowed_methods | Matches the request method. | ['*'] |
allowed_origins | Matches the request origin. Wildcards can be used, eg. *.mydomain.com or mydomain.com:* | ['*'] |
allowed_origins_patterns | Matches the request origin with preg_match . | [] |
allowed_headers | Sets the Access-Control-Allow-Headers response header. | ['*'] |
exposed_headers | Sets the Access-Control-Expose-Headers response header. | [] |
max_age | Sets the Access-Control-Max-Age response header. | 0 |
supports_credentials | Sets the Access-Control-Allow-Credentials header. | false |
allowed_origins
, allowed_headers
and allowed_methods
can be set to ['*']
to accept any value.
Note: For
allowed_origins
you must include the scheme when not using a wildcard, eg.['http://example.com', 'https://example.com']
. You must also take into account that the scheme will be present when usingallowed_origins_patterns
.
Note: Try to be as specific as possible. You can start developing with loose constraints, but it's better to be as strict as possible!
Note: Because of http method overriding in Laravel, allowing POST methods will also enable the API users to perform PUT and DELETE requests as well.
Note: Sometimes it's necessary to specify the port (when you're coding your app in a local environment for example). You can specify the port or using a wildcard here too, eg.
localhost:3000
,localhost:*
or even using a FQDNapp.mydomain.com:8080
Lumen
On Lumen, just register the ServiceProvider manually in your bootstrap/app.php
file:
$app->register(Fruitcake\Cors\CorsServiceProvider::class);
Also copy the cors.php config file to config/cors.php
and put it into action:
$app->configure('cors');
Global usage for Lumen
To allow CORS for all your routes, add the HandleCors
middleware to the global middleware and set the paths
property in the config.
$app->middleware([
// ...
Fruitcake\Cors\HandleCors::class,
]);
Common problems
Wrong config
Make sure the path
option in the config is correct and actually matches the route you are using. Remember to clear the config cache as well.
Error handling, Middleware order
Sometimes errors/middleware that return own responses can prevent the CORS Middleware from being run. Try changing the order of the Middleware and make sure it's the first entry in the global middleware, not a route group. Also check your logs for actual errors, because without CORS, the errors will be swallowed by the browser, only showing CORS errors. Also try running it without CORS to make sure it actually works.
Authorization headers / Credentials
If your Request includes an Authorization header or uses Credentials mode, set the supports_credentials
value in the config to true. This will set the Access-Control-Allow-Credentials Header to true
.
Echo/die
If you use echo()
, dd()
, die()
, exit()
, dump()
etc in your code, you will break the Middleware flow. When output is sent before headers, CORS cannot be added. When the script exits before the CORS middleware finishes, CORS headers will not be added. Always return a proper response or throw an Exception.
Disabling CSRF protection for your API
If possible, use a route group with CSRF protection disabled.
Otherwise you can disable CSRF for certain requests in App\Http\Middleware\VerifyCsrfToken
:
protected $except = [
'api/*',
'sub.domain.zone' => [
'prefix/*'
],
];
Duplicate headers
The CORS Middleware should be the only place you add these headers. If you also add headers in .htaccess, nginx or your index.php file, you will get duplicate headers and unexpected results.
No Cross-Site requests
If you are not doing Cross-Site requests, meaning if you are not requesting site-a.com/api from site-b.com, your browser will not send the Origin: https://site-b.com
request header, CORS will be "disabled" as the Access-Control-Allow-Origin
header will be also missing. This happens because requests are being dispatched from the same and no protection is needed in this case.
License
Released under the MIT License, see LICENSE.
Top Related Projects
Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
Cross-origin resource sharing library and stack middleware.
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot