Milind Daraniya

How to Fix Token Mismatch Exception in Laravel

Published August 1st, 2023 24 min read

The "TokenMismatchException" is a common issue encountered when working with forms in Laravel. This exception occurs when the CSRF token provided by Laravel's CSRF protection middleware does not match the token sent with the form request. In this tutorial, we'll guide you through the process of fixing the TokenMismatchException in Laravel. Let's get started!

Understand CSRF Protection in Laravel 
Cross-Site Request Forgery (CSRF) is an attack that tricks users into unintentionally submitting malicious requests. Laravel includes built-in CSRF protection to prevent this attack by generating and validating CSRF tokens for form submissions.

Verify CSRF Token in Form Requests 
To fix the TokenMismatchException, ensure that your forms include the CSRF token. Laravel provides a convenient way to include the token using the @csrf Blade directive. Make sure your form includes this directive within the <form> tags, like so:

<form method="POST" action="/example">
    @csrf
    <!-- Rest of the form fields -->
    <button type="submit">Submit</button>
</form>

Check CSRF Middleware 
Laravel automatically applies the VerifyCsrfToken middleware to your routes, which verifies the CSRF token for each POST, PUT, PATCH, and DELETE request. Ensure that your form submission is handled by a route that is protected by this middleware.

Verify CSRF Token in AJAX Requests 
When making AJAX requests, you need to ensure that the CSRF token is included in the request headers. In your JavaScript code, include the token in the headers of your AJAX requests as shown in the following example:

$.ajax({
    url: '/example',
    type: 'POST',
    data: {
        // Your request data
    },
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function(response) {
        // Handle the response
    },
    error: function(xhr) {
        // Handle the error
    }
});

Make sure to replace /example with the actual URL of your AJAX request.

Verify CSRF Token in API Requests 
If you're working with API routes, you may need to handle CSRF protection differently. By default, Laravel's api middleware group does not include CSRF protection. You can either add the web middleware group to your API routes or exclude CSRF protection for specific API routes.

To add the web middleware group to your API routes, modify the RouteServiceProvider located in app/Providers/RouteServiceProvider.php as follows:

protected function mapApiRoutes()
{
    Route::middleware('web')
         ->prefix('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

Remember to clear the application cache using the command php artisan route:cache after modifying the RouteServiceProvider.

Happy coding and stay secure! 🔒🌐