How to Fix CORS Error in Laravel: Simple Steps
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 // routes/api.php Route::get('/data', function () { return ['message' => 'Hello from API']; });
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 // config/cors.php return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://frontend-app'], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
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.