CORS Error in Laravel - How to Fix Cross-Origin Issues
CORS errors occur when a frontend application tries to access a Laravel API from a different origin (domain, port, or protocol).
The Error
CORS error / Access-Control-Allow-Origin blocked
Common Causes
- 1 CORS middleware not configured
- 2 Missing Access-Control-Allow-Origin header
- 3 Preflight OPTIONS request not handled
- 4 Credentials not allowed in CORS config
Solutions
Configure CORS in config/cors.php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:3000', 'https://yourfrontend.com'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
For Laravel 11+ with Sanctum SPA
// In .env
SANCTUM_STATEFUL_DOMAINS=localhost:3000,yourfrontend.com
SESSION_DOMAIN=.yourdomain.com
Frontend request with credentials
axios.defaults.withCredentials = true;
fetch('/api/user', {
credentials: 'include'
});
Need Help With Your Laravel Project?
I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.
Currently available for 2-3 new projects
About Hafiz
Senior Full-Stack Developer with 9+ years building web apps and SaaS platforms. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.
View Portfolio