How To Exclude Routes From CSRF Checks in Laravel 11

June 18th, 2024 • 1 minute read time

Laravel 11 changes how you disable CSRF checks on routes thanks to its slimmed-down boilerplate. Here's how to disable CSRF checks from Laravel 11 onwards.

Start by opening the bootstrap/app.php file for your project. Here, you'll see a withMiddleware method is invoked, with the option to customise this with a callback.

->withMiddleware(function (Middleware $middleware) {
    //
})

To exclude any routes from CSRF checks, chain onto the Middleware object with the validateCsrfTokens and provide the except parameter:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/*',
    ]);
})

Here, we're using a wildcard to exclude any routes that start with stripe/, but you can also provide set paths.

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/webhook',
    ]);
})

While this method of excluding routes from CSRF tokens has changed a lot since Laravel 10, it's allowed for the removal of the VerifyCsrfToken middleware in previous versions to provide a cleaner boilerplate.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under