Are you happy with your logging solution? Would you help us out by taking a 30-second survey? Click here

laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application

Subscribe to updates I use laravel-cors


Statistics on laravel-cors

Number of watchers on Github 2462
Number of open issues 17
Average time to close an issue 18 days
Main language PHP
Average time to merge a PR 6 days
Open pull requests 13+
Closed pull requests 10+
Last commit almost 2 years ago
Repo Created about 6 years ago
Repo Last Updated over 1 year ago
Size 126 KB
Organization / Authorbarryvdh
Latest Releasev0.11.0
Contributors10
Page Updated
Do you use laravel-cors? Leave a review!
View open issues (17)
View laravel-cors activity
View on github
Fresh, new opensource launches πŸš€πŸš€πŸš€
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating laravel-cors for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

CORS Middleware for Laravel 5

Latest Version on Packagist Software License Build Status Total Downloads

Based on https://github.com/asm89/stack-cors

About

The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

If you want to have have a global overview of CORS workflow, you can browse this image.

Features

  • Handles CORS pre-flight OPTIONS requests
  • Adds CORS headers to your responses

Installation

Require the barryvdh/laravel-cors package in your composer.json and update your dependencies:

$ composer require barryvdh/laravel-cors

For laravel >=5.5 that's all. This package supports Laravel new Package Discovery.

If you are using Laravel < 5.5, you also need to add Cors\ServiceProvider to your config/app.php providers array:

Barryvdh\Cors\ServiceProvider::class,

Global usage

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

Group middleware

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

Configuration

The defaults are set in config/cors.php. Copy this file to your own config directory to modify the values. You can publish the config using this command:

$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Note: When using custom headers, like X-Auth-Token or X-Requested-With, you must set the allowedHeaders to include those headers. You can also set it to array('*') 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.

return [
     /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
]

allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') to accept any value.

Note: Try to be a 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.

Lumen

On Laravel Lumen, load your configuration file manually in bootstrap/app.php:

$app->configure('cors');

And register the ServiceProvider:

$app->register(Barryvdh\Cors\ServiceProvider::class);

Global usage for Lumen

To allow CORS for all your routes, add the HandleCors middleware to the global middleware:

$app->middleware([
    // ...
    \Barryvdh\Cors\HandleCors::class,
]);

Group middleware for Lumen

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

$app->routeMiddleware([
    // ...
    'cors' => \Barryvdh\Cors\HandleCors::class,
]);

Common problems and errors (Pre Laravel 5.3)

In order for the package to work, the request has to be a valid CORS request and needs to include an Origin header.

When an error occurs, the middleware isn't run completely. So when this happens, you won't see the actual result, but will get a CORS error instead.

This could be a CSRF token error or just a simple problem.

Note: This should be working in Laravel 5.3+.

Disabling CSRF protection for your API

If possible, use a different route group with CSRF protection enabled. Otherwise you can disable CSRF for certain requests in App\Http\Middleware\VerifyCsrfToken:

protected $except = [
    'api/*'
];

License

Released under the MIT License, see LICENSE.

laravel-cors open issues Ask a question     (View All Issues)
  • almost 3 years Invalid origin pattern when using Postman
  • almost 3 years 302 redirect when using Laravel's Form Request Validation
  • about 3 years typo on pathMaches()
  • about 3 years laravel-cors includes the asm89 cors middleware when it shouldn't
  • about 3 years Allow CORS from users who have signed up
  • about 3 years UnexpectedValueException
  • about 3 years Error Cors Laravel 5.3 y Angular 1.5.8
  • about 3 years Works locally but not from other machines
  • about 3 years Error (No 'Access-Control-Allow-Origin' header is present on the requested resource.)
  • about 3 years 403 for POSTS with Postman
  • about 3 years No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • over 3 years Route::controller() and $this->middleware('cors')
  • over 3 years No CORS-Headers sent in Lumen 5.2
  • over 3 years Access-Control-Allow-Headers in OPTIONS not sending
  • over 3 years custom headers must be setup explicitly, it wont work if you just setup asterisk * symbol
  • over 3 years Laravel 5.2.24. Class HandlePreflight does not work for OPTIONS request
  • over 3 years Laravel 5.2.24 "Class cors does not exists"
  • over 3 years the thing with the cors issue is getting tough
  • over 3 years Change the README, because CSRF works properly
  • over 3 years Laravel 5.2 Request header field Content-Type is not allowed
  • over 3 years Handle 'X-Requested-with' from the Hybrid App
  • over 3 years Preflight requests not testable with lumen's TestCase
  • over 3 years Preflight Exceptions
  • over 3 years Just stopped working all together?
  • almost 4 years [fixed] laravel-cors not working
  • almost 4 years Not working on IIS 7.5
  • almost 4 years Conflict with middleware that returns new response
  • almost 4 years Laravel 5.1 / Forge Cors 404
  • almost 4 years using laravel 5.1.x, the cors doesn't work together with the jwt.auth package
  • almost 4 years Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
laravel-cors open pull requests (View All Pulls)
  • Update HandlePreflight to avoid returning wrong status code
  • Applied fixes from StyleCI
  • Add missing PHPDoc argument
  • Add missing PHPDoc argument
  • path config ported
  • add: support for defining origins by regExp
  • Update readme.md
  • Extending OriginMatcher to support non-http/-https origins, in partic…
  • add allowedHeaders info to response header while dingo api return 4xx…
  • Make the config file compliant with other Laravel's config files
  • Simplify preflight
  • Use upstream asm
  • Update license year
laravel-cors questions on Stackoverflow (View All Questions)
  • Laravel Cors No 'Access-Control-Allow-Origin'
  • Laravel CORS subdomain session
  • laravel cors "Class cors does not exist" error
  • Laravel CORS middleware fails for post and resource request
  • AngularJS & Laravel CORS, POST stops after preflights OPTIONS
  • Angular/Laravel CORS issue : The Same Origin Policy disallows reading the remote resource
  • Laravel and CORS with barryvdh/laravel-cors
  • Laravel angularJS CORS using barryvdh/laravel-cors not working on IIS
  • Angularjs 'Access-Control-Allow-Origin' using Laravel CORS
  • AngularJS and Laravel - CORS
  • Enabling CORS in laravel using barryvdh/laravel-cors package?
  • Laravel - cross domain request - barryvdh laravel-cors
  • Laravel angularJS CORS using barryvdh/laravel-cors
laravel-cors list of languages used
laravel-cors latest release notes
v0.11.0 Use upstream asm/stack-cors

Breaking changes

  • The wildcard matcher is changed. You can use allowedOriginPatterns for your own patterns, or simple wildcards in the normal origins. Eg. *.laravel.com should still work.

Changes

  • Uses upstream asm/stack-cors (see #195)
  • Move tests to namespaces (See #277)
v0.10.1 Fix preflight status
v0.10.0
Other projects in PHP