Api
Laravel 8
Laravel 9
Laravel 10
Laravel 11
Laravel 12
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
Error Message
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
1
Configure CORS in config/cors.php
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,
];
2
For Laravel 11+ with Sanctum SPA
ENV
// In .env
SANCTUM_STATEFUL_DOMAINS=localhost:3000,yourfrontend.com
SESSION_DOMAIN=.yourdomain.com
3
Frontend request with credentials
JavaScript
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
Full Stack Developer from Italy. I build web applications with Laravel and Vue.js, and automate business processes. Creator of ReplyGenius, StudyLab, and other SaaS products.
View Portfolio