0
0
LaravelDebug / FixBeginner · 4 min read

How to Fix CORS Error in Laravel: Simple Steps

To fix a CORS error in Laravel, you need to properly configure the cors.php config file and ensure the HandleCors middleware is enabled in your HTTP kernel. This allows your Laravel app to accept requests from different origins safely.
🔍

Why This Happens

A CORS error happens when your Laravel backend blocks requests coming from a different domain or port than itself. Browsers enforce this to protect users from malicious sites. If your Laravel app does not send the right headers allowing cross-origin requests, the browser will stop the request and show a CORS error.

php
<?php
// routes/api.php
Route::get('/data', function () {
    return ['message' => 'Hello from API'];
});
Output
Access to fetch at 'http://your-laravel-app/api/data' from origin 'http://frontend-app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
🔧

The Fix

To fix this, install and configure Laravel's fruitcake/laravel-cors package (included by default in Laravel 9+). Then, publish the config file and set allowed origins, methods, and headers. Make sure the HandleCors middleware is active in app/Http/Kernel.php. This setup sends the correct headers to allow cross-origin requests.

php
<?php
// config/cors.php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['http://frontend-app'],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];
Output
The API responds with the correct CORS headers, allowing the frontend app to access the data without errors.
🛡️

Prevention

Always configure CORS early when building APIs to avoid blocking frontend requests. Use environment variables to manage allowed origins for different environments (development, staging, production). Regularly update Laravel and the CORS package to get security fixes. Test your API with tools like Postman and browser DevTools to verify CORS headers.

⚠️

Related Errors

Other common errors include CSRF token mismatch when using cookies with CORS, which requires enabling supports_credentials and proper token handling. Also, preflight request failures happen if the server does not respond correctly to OPTIONS requests; ensure your middleware handles OPTIONS method.

Key Takeaways

Configure the cors.php file to allow your frontend origin.
Enable the HandleCors middleware in app/Http/Kernel.php.
Use environment variables to manage allowed origins securely.
Test CORS behavior using browser DevTools or API clients.
Keep Laravel and CORS packages updated for best security.