Laravel how to disable Cors

"Learn how to easily disable CORS in Laravel with a step-by-step example."

Disabling CORS in Laravel

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin access to selected resources from a different origin. It is a mechanism that allows restricted resources from a webpage to be requested from another domain outside the domain from which the resource originated. In Laravel, CORS can be disabled using the middleware. Middleware is code that is run before and after your route is executed.
// Within AppHttpKernel class
protected $middlewareGroups = [
    'web' => [
        // Other middleware...
        BarryvdhCorsHandleCors::class,
    ],
];
The HandleCors class is responsible for applying the CORS headers to each request. This can be configured by creating a new cors.php file in the config folder.
// Within config/cors.php
return [
    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
     */
    'allowed_origins' => ['*'],

    /*
     * Patterns that can be used with `preg_match` to match the origin.
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header with these headers.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header when > 0.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];
The above configuration will disable CORS for the ‘api/*’ route. You can also specify different middleware for different routes. To disable CORS for all routes, you can set ‘paths’ to ‘*’. Finally, you can also disable CORS in routes/api.php. To do this, you need to add the following line of code to the route:
Route::middleware('cors')->get('/api/foo', function () {
    //
});
This will disable CORS for the ‘api/foo’ route. In summary, CORS can be disabled in Laravel for specific routes or for all routes. This can be done by configuring the HandleCors middleware or by adding the cors middleware to your routes.

Answers (0)