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
.