Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel 11 fruitcake/laravel-cors


Laravel 11 fruitcake/laravel-cors


To use the fruitcake/laravel-cors package in Laravel, follow these steps:

1. Install the package via Composer:

bash
composer require fruitcake/laravel-cors

2. Add the CORS middleware to the global middleware stack in `app/Http/Kernel.php`:

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

3. Configure the CORS settings in the `config/cors.php` file:

php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];

This configuration allows CORS for all routes starting with `/api/` and the `/sanctum/csrf-cookie` route, using the `*` wildcard to allow all methods, origins, and headers[1][4].

4. If you're using Laravel 9 or higher, you can replace the `\Fruitcake\Cors\HandleCors::class` middleware with `\Illuminate\Http\Middleware\HandleCors::class` as it is now included in the core framework[2].

Here's a sample code snippet to demonstrate how to use CORS in a Laravel API route:

php
Route::get('/users', function () {
    return User::all();
})->middleware('cors');

In this example, the `cors` middleware is applied to the `/users` route, allowing cross-origin requests to fetch all users[1][4].

By following these steps and configuring the CORS settings according to your application's needs, you can enable CORS support in your Laravel application and allow cross-origin requests to access your API or specific routes[4].

Citations:
[1] https://github.com/fruitcake/laravel-cors
[2] https://stackoverflow.com/questions/76537955/how-to-resolve-cors-issue-in-laravel-version-10
[3] https://laracasts.com/discuss/channels/laravel/fruitcake-laravel-cors-package-issue
[4] https://www.stackhawk.com/blog/laravel-cors/
[5] https://github.com/fruitcake/laravel-cors/blob/master/composer.json

How to use built-in CORS

To resolve CORS issues in Laravel 10 or 11 without using the deprecated `fruitcake/laravel-cors` package, you can use the built-in `HandleCors` middleware provided by Laravel:

1. Remove the `fruitcake/laravel-cors` package from your `composer.json` file and run `composer update` to update your dependencies[1].

2. In your `app/Http/Kernel.php` file, replace `\Fruitcake\Cors\HandleCors::class` with `\Illuminate\Http\Middleware\HandleCors::class` in the `$middleware` array[1][3].

3. Configure the CORS settings in your `config/cors.php` file. You can specify the allowed origins, headers, methods, etc. Here's an example configuration:

php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];

4. If you're using Lumen, register the `HandleCors` middleware in your `bootstrap/app.php` file[1]:

php
$app->middleware([
    \Illuminate\Http\Middleware\HandleCors::class,
]);

5. Copy the `cors.php` config file from the `vendor/laravel/framework/src/Illuminate/Foundation/Application/cors.php` path to your `config` directory and configure it according to your needs[1].

By following these steps, you should be able to resolve the CORS issues in your Laravel 10 or 11 application without using the deprecated `fruitcake/laravel-cors` package.

Citations:
[1] https://github.com/fruitcake/laravel-cors
[2] https://github.com/fruitcake/laravel-cors/releases
[3] https://stackoverflow.com/questions/76537955/how-to-resolve-cors-issue-in-laravel-version-10
[4] https://packagist.org/packages/fruitcake/php-cors
[5] https://www.youtube.com/watch?v=nyoWb8cz2b4

Customizing CORS Settings

Open the `config/cors.php` file to customize your CORS settings. Here’s an example configuration:

php
return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'], // Specify paths where CORS should be applied

    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'], // HTTP methods allowed

    'allowed_origins' => ['https://example.com', 'https://another-domain.com'], // Allowed origins

    'allowed_origins_patterns' => [], // Patterns for matching origins

    'allowed_headers' => ['Content-Type', 'X-Requested-With'], // Headers allowed in requests

    'exposed_headers' => ['Authorization', 'X-Custom-Header'], // Headers exposed in responses

    'max_age' => 3600, // Max age for the preflight request (in seconds)

    'supports_credentials' => true, // Whether credentials are supported
];

Applying CORS to Specific Routes

If you prefer to apply CORS settings to specific routes or route groups, you can use route middleware. First, define the middleware in `app/Http/Kernel.php`:

php
protected $routeMiddleware = [
    // ...
    'cors' => \Fruitcake\Cors\HandleCors::class,
];

Then, apply the middleware to your routes in `routes/web.php` or `routes/api.php`:

php
Route::group(['middleware' => ['cors']], function () {
    Route::get('/example', 'ExampleController@index');
    Route::post('/example', 'ExampleController@store');
});

Dynamic CORS Configuration

If you need dynamic CORS settings based on the request, you can create custom middleware. Here’s an example:

1. Create a new middleware using the Artisan command:

bash
    php artisan make:middleware CustomCors
    

2. In `app/Http/Middleware/CustomCors.php`, add the following logic:

php
    namespace App\Http\Middleware;

    use Closure;
    use Fruitcake\Cors\HandleCors;

    class CustomCors extends HandleCors
    {
        public function handle($request, Closure $next)
        {
            // Customize CORS settings based on the request
            $this->options['allowed_origins'] = ['https://dynamic-origin.com'];

            return parent::handle($request, $next);
        }
    }
    

3. Register the custom middleware in `app/Http/Kernel.php`:

php
    protected $routeMiddleware = [
        // ...
        'custom.cors' => \App\Http\Middleware\CustomCors::class,
    ];
    

4. Apply the custom middleware to your routes:

php
    Route::group(['middleware' => ['custom.cors']], function () {
        Route::get('/dynamic', 'DynamicController@index');
    });