Laravel CORS (Cross-Origin Resource Sharing) provides support for handling requests from different domains. Laravel uses the package fruitcake/laravel-cors
to allow the configuration of CORS headers. CORS is essential for enabling secure communication between web applications hosted on different domains, particularly in scenarios like API access or loading resources from external sources.
Installation of Laravel CORS
To install the Laravel CORS package, you can use Composer:
1 |
composer require fruitcake/laravel-cors |
This will install the fruitcake/laravel-cors
package, which handles the configuration and management of CORS requests in your Laravel application.
Configuration
After installation, you can configure CORS in the config/cors.php
file. If this file does not exist, you can publish the configuration file using this command:
1 |
php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider" |
Once the file is published, you will find it under config/cors.php
. It contains a set of configuration options that define how your application handles CORS.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], // Define which paths should be handled for CORS 'allowed_methods' => ['*'], // Define allowed HTTP methods (GET, POST, etc.) 'allowed_origins' => ['*'], // Define allowed origins (e.g., http://example.com or *) 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], // Define allowed headers (e.g., X-Custom-Header or *) 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, // Define whether credentials like cookies should be included ]; |
Important Configuration Options
paths
: The routes or paths where CORS should be applied. For example, if you’re building an API, you might want to apply CORS to all API routes (api/*
).allowed_methods
: HTTP methods that are allowed from other origins. You can set it to['*']
to allow all methods or specify specific methods like['GET', 'POST']
.allowed_origins
: The origins (domains) that are allowed to make requests. You can use['*']
to allow all origins, or specify specific domains like['https://example.com']
.allowed_headers
: Headers that are allowed from external requests. You can allow all headers with['*']
or specify certain headers like['Content-Type', 'X-Requested-With']
.supports_credentials
: Set this totrue
if you want to allow cross-origin requests with credentials (like cookies).
Example Configuration
If you want to allow requests from a specific domain and allow certain methods, your cors.php
might look like this:
1 2 3 4 5 6 7 |
return [ 'paths' => ['api/*'], 'allowed_methods' => ['GET', 'POST', 'DELETE'], 'allowed_origins' => ['https://mydomain.com'], 'allowed_headers' => ['Content-Type', 'Authorization'], 'supports_credentials' => true, ]; |
Applying CORS Middleware
Once the CORS configuration is set up, you need to ensure that the middleware is enabled. In app/Http/Kernel.php
, ensure that the \Fruitcake\Cors\HandleCors::class
middleware is added to the global
middleware stack:
1 2 3 4 |
protected $middleware = [ // Other middleware \Fruitcake\Cors\HandleCors::class, ]; |
This will ensure that CORS is applied to all incoming requests. If you need more specific control, you can also apply the middleware to individual routes or groups.
CORS Error Example and Resolution
If you encounter a CORS error when making an API call from a different domain, you might see an error in the browser console like this:
1 |
Access to XMLHttpRequest at 'https://api.example.com/data' from origin 'https://mydomain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. |
By properly configuring CORS in Laravel using the steps above, this error will be resolved, and the appropriate headers will be sent to allow cross-origin requests.
Testing CORS Configuration
You can test your CORS setup by making an AJAX request or an API call from a different domain. For example, using JavaScript’s fetch
API:
1 2 3 4 5 6 7 |
fetch('https://api.example.com/data', { method: 'GET', credentials: 'include' // Include cookies in the request }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log('Error:', error)); |
If your CORS is configured correctly, the request will go through without any issues.
Summary:
- Install the
fruitcake/laravel-cors
package using Composer. - Configure allowed origins, methods, and headers in
config/cors.php
. - Ensure the CORS middleware is enabled in
app/Http/Kernel.php
. - Test the setup by making cross-origin requests from external domains.
Output
The output for configuring CORS in Laravel can be observed through various scenarios, depending on how your application is set up to handle Cross-Origin Resource Sharing.
1. Successful CORS Configuration
If you have successfully configured CORS, when an external client (e.g., a frontend app) sends a request to your Laravel API, the browser will include the correct CORS headers in the request and response.
Request Headers
From the frontend, the browser will send a preflight request (an OPTIONS
request) to check if the API allows cross-origin requests.
Example OPTIONS
Request:
1 2 3 4 5 |
OPTIONS /api/data HTTP/1.1 Host: api.example.com Origin: https://frontend.example.com Access-Control-Request-Method: GET Access-Control-Request-Headers: content-type |
Response Headers
If the CORS configuration is correct, the response from the Laravel API will contain the following headers:
1 2 3 4 |
HTTP/1.1 200 OK Access-Control-Allow-Origin: https://frontend.example.com Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Content-Type, Authorization |
This indicates that the request is allowed, and the frontend can access the data. The request will proceed successfully.
2. CORS Error: Missing or Invalid Configuration
If the CORS configuration is missing or invalid, the browser will block the request, and you’ll see an error in the developer console. The request will fail with a CORS policy error.
Example CORS Error:
1 |
Access to XMLHttpRequest at 'https://api.example.com/data' from origin 'https://frontend.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. |
Access-Control-Allow-Origin
header, or the origin specified in the request is not allowed in the CORS configuration.
3. Request with Credentials
If you set supports_credentials
to true
in your CORS configuration and the frontend includes credentials (like cookies or HTTP authentication), the response will also include the Access-Control-Allow-Credentials
header.
Example Request:
1 2 3 4 5 6 |
fetch('https://api.example.com/data', { method: 'GET', credentials: 'include', // Sends cookies along with the request }) .then(response => response.json()) .then(data => console.log(data)); |
Response Headers:
1 2 3 4 5 |
HTTP/1.1 200 OK Access-Control-Allow-Origin: https://frontend.example.com Access-Control-Allow-Methods: GET, POST Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Credentials: true |
4. CORS Preflight Requests
If the request involves non-simple HTTP methods like PUT
, PATCH
, or DELETE
, the browser will make a preflight request using the OPTIONS
method before sending the actual request.
Preflight Request:
1 2 3 4 |
OPTIONS /api/data HTTP/1.1 Origin: https://frontend.example.com Access-Control-Request-Method: PUT Access-Control-Request-Headers: Content-Type |
Preflight Response:
1 2 3 4 |
HTTP/1.1 204 No Content Access-Control-Allow-Origin: https://frontend.example.com Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Content-Type |
If the preflight request is successful, the browser will proceed with the actual request.
Summary of Outputs:
- Successful Request: Includes
Access-Control-Allow-Origin
and other CORS headers in the response. - CORS Error: Browser blocks the request due to missing CORS headers, with an error in the console.
- Credentials Request: Includes
Access-Control-Allow-Credentials
in the response when cookies or credentials are sent. - Preflight Request: Includes CORS headers in the response to allow non-simple HTTP methods like
PUT
orDELETE
.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling