From d2d7c153bf82a340b911144524cdf43ce659563b Mon Sep 17 00:00:00 2001 From: Wendell Adriel Date: Fri, 20 Mar 2026 19:20:51 +0000 Subject: [PATCH] Add documentation for route-specific CORS --- routing.md | 93 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/routing.md b/routing.md index c5a91f72d0..1e68e724ba 100644 --- a/routing.md +++ b/routing.md @@ -28,6 +28,7 @@ - [Form Method Spoofing](#form-method-spoofing) - [Accessing the Current Route](#accessing-the-current-route) - [Cross-Origin Resource Sharing (CORS)](#cors) + - [Route-specific CORS](#route-specific-cors) - [Route Caching](#route-caching) @@ -1045,6 +1046,98 @@ php artisan config:publish cors This command will place a `cors.php` configuration file within your application's `config` directory. + +### Route-specific CORS + +If you need different CORS policies for different parts of your application, you may define CORS options directly on individual routes or route groups. Route-specific CORS options override the global CORS configuration for the matched route. The `cors` method accepts `origins`, `methods`, `headers`, `exposed_headers`, `max_age`, and `credentials` options. + +```php +use Illuminate\Support\Facades\Route; + +Route::get('/profile', function () { + // ... +})->cors([ + 'origins' => ['https://app.example.com'], + 'methods' => ['GET'], + 'headers' => ['Content-Type', 'X-Requested-With'], +]); +``` + +You may also apply the same CORS options to every route within a route group: + +```php +use Illuminate\Support\Facades\Route; + +Route::prefix('api') + ->cors([ + 'origins' => ['https://frontend.example.com'], + 'methods' => ['GET', 'POST'], + ]) + ->group(function () { + Route::get('/reports', function () { + // ... + }); + + Route::post('/reports', function () { + // ... + }); + }); +``` + +If you are defining controller routes, you may use the `Illuminate\Routing\Attributes\Cors` attribute on the controller class or on individual controller methods: + +```php + [!NOTE] > For more information on CORS and CORS headers, please consult the [MDN web documentation on CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers).