In Laravel 11, you can disable CSRF protection for specific routes by using the `withMiddleware()` method in the `bootstrap/app.php` file. Here's how you can do it:
1. Open the `bootstrap/app.php` file.
2. Locate the `withMiddleware()` method and add the following code to disable CSRF protection for specific routes:
php
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
// Disable CSRF protection for specific routes
$middleware->validateCsrfTokens(except: [
'stripe/*',
'https://example.com/foo/bar',
'https://example.com/foo/*',
]);
})
// Other configuration
->create();
In this example, the `validateCsrfTokens()` method is used to specify the routes that should be excluded from CSRF protection. You can add as many routes as needed to the `except` array.
The routes can be specified using wildcards (`*`) or as full URLs. In the example above, the following routes will be excluded from CSRF protection:
- All routes starting with `stripe/`
- The route `https://example.com/foo/bar`
- All routes starting with `https://example.com/foo/`
Keep in mind that disabling CSRF protection can make your application more vulnerable to cross-site request forgery attacks, so it's generally recommended to only disable it for specific routes that require it, such as webhooks or external API integrations.
Citations:[1] https://securinglaravel.com/security-tip-laravel-11s-middleware/
[2] https://github.com/spatie/laravel-support-bubble/discussions/50
[3] https://stackoverflow.com/questions/37806762/how-to-disable-csrf-token-in-laravel-and-why-we-have-to-disable-it
[4] https://bagisto.com/en/how-to-disable-csrf-token-for-specific-routes-in-laravel/
[5] https://laravel.com/docs/11.x/csrf