Laravel 11 CORS Middleware Configuration Example

By Hardik Savani September 4, 2024 Category : Laravel

In this post, I will show you how to customize cors middleware in laravel 11 application. By default enable cors middleware with default configuration in laravel 11.

What is CORS Middleware in Laravel?

CORS (Cross-Origin Resource Sharing) middleware in Laravel allows your web application to safely request resources from a different origin (domain) than its own. This is useful for APIs and web services. The middleware checks and approves these cross-origin requests, ensuring they meet specified security policies. In Laravel, you can easily set up and configure CORS middleware to control which external sites can access your application's resources.

Laravel 11 can automatically respond to CORS OPTIONS HTTP requests with the settings you choose. The OPTIONS requests are handled by the HandleCors middleware, which is already included in your application's global middleware stack.

Sometimes, you might need to change the CORS settings for your application. You can do this by publishing the cors configuration file using the config:publish artisan command:

php artisan config:publish cors

Now, above command added new "cors.php" config file, you can update options as your requirement.

config/cors.php

<?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.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

You can change the settings of allowed methods, origins, headers etc.

I hope it can help you...

Shares