How to Fix CORS Error in Laravel
One of the common errors developers face when connecting the Frontend with the API in Laravel is the error: "Access to fetch has been blocked by CORS policy". This error is not caused by an issue in your code itself, but rather due to the browser’s default security settings.
What is CORS?
CORS stands for Cross-Origin Resource Sharing, which is a security mechanism in browsers that prevents sending requests between different domains unless the server explicitly allows it.
For example, if your frontend is running on: http://localhost:3000 and your API is running on: http://localhost:8000, the browser will block the connection unless permission is granted in the CORS settings.
The Cause of the Problem
By default, the browser does not trust requests coming from external domains to prevent unauthorized data access or hacking attempts. So, when the server response does not include CORS settings, the request is blocked and the error appears.
Managing CORS in Laravel
In older versions of Laravel (before version 9), developers needed to install an external package like:
composer require fruitcake/laravel-cors However, in modern versions (Laravel 9 to Laravel 11), CORS settings are built-in through the HandleCors middleware, without needing any additional packages.
How to Configure the Settings
To allow the frontend to communicate with the API, modify the CORS configuration in the following file:
config/cors.php For quick testing, you can use these settings:
return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://localhost:3000'], 'allowed_headers' => ['*'], ]; Also, make sure that: \Illuminate\Http\Middleware\HandleCors::class is included in the middleware list inside: app/Http/Kernel.php.
After Configuration
Once the settings are configured correctly, the frontend will be able to send requests to the API without any CORS-related issues. No temporary or unsafe workarounds are needed.
Conclusion
A CORS error does not mean there is something wrong with your code — it is simply a security layer that needs proper configuration. With the latest Laravel updates, managing it has become easier and clearer.
Starting from Laravel 9, CORS settings are integrated into the framework — just edit the values in config/cors.php, and everything will work smoothly.