I am currently working with Laravel 12.13 and facing an issue with CORS. I have configured the HandleCors middleware and the CORS settings in my application, but I am still getting CORS errors when trying to make requests from the frontend to the backend.
Here’s what I have done so far:
In bootstrap/app.php, I have added the following middleware configuration:
<?php use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Register native CORS middleware in Laravel 12
$middleware->append(IlluminateHttpMiddlewareHandleCors::class);
// You can add other global middleware here
})
->withExceptions(function (Exceptions $exceptions) {
//
})
->create();
I have created the cors.php configuration file inside the config directory with the following content:
<?php
return [
'paths' => ['api/v1/*'],
// Methods I want to allow for CORS:
'allowed_methods' => ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'],
// Origins from where I allow access without CORS interference:
'allowed_origins' => ['https://annaponsprojects.com'],
'allowed_origins_patterns' => [],
// Headers I want to allow to receive in frontend requests:
'allowed_headers' => ['Content-Type', 'Authorization', 'Accept'],
'exposed_headers' => [],
// Don't perform preflight until 1 hour has passed:
'max_age' => 3600,
// Indicates if the browser can send cookies (works with tokens):
'supports_credentials' => false ];
However, I am still encountering CORS issues when sending a request from the frontend to my backend API. The error message I receive is:
Access to fetch at ” from origin ” has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
What have I tried so far?
I’ve made sure to include the correct middleware (HandleCors) in the bootstrap/app.php.
I’ve configured CORS settings in the config/cors.php file.
I’ve cleared the cache (php artisan config:clear and php artisan cache:clear).
What could I be missing?
I suspect the issue might be related to the CORS configuration, but I am not sure. Is there anything else I should check or configure in Laravel 12.13 to resolve this issue?