Laravel CSRF Token Mismatch for Ajax POST Request - Solution

Published on
2 mins read
––– views

Laravel CSRF Token Mismatch for Ajax POST Request - Solution

When encountering the "CSRF Token Mismatch" error for Ajax POST requests in Laravel, it indicates an issue with CSRF protection. Here's how you can resolve it:

1. Include CSRF Token in Ajax Requests

Ensure that your Ajax requests include the CSRF token. Laravel provides a convenient way to include it in the global JavaScript variable window.Laravel.

In your Blade template, add the following script to include the CSRF token:

<script>
    window.Laravel = {!! json_encode(['csrfToken' => csrf_token()]) !!};
</script>

2. Pass CSRF Token in Ajax Headers

Modify your Ajax requests to include the CSRF token in the headers.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': window.Laravel.csrfToken
    }
});

// Your Ajax request
$.ajax({
    // ...
    data: {
        // Other data
    },
    success: function(response) {
        // Handle success
    },
    error: function(error) {
        // Handle error
    }
});

3. Check CSRF Token Middleware

Ensure that the web middleware group, which includes the VerifyCsrfToken middleware, is applied to your routes. This middleware checks the CSRF token for non-GET, HEAD, or OPTIONS requests.

// In app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];

4. Verify CSRF Token in Controller

If you're still facing issues, manually verify the CSRF token in your controller method.

use Illuminate\Support\Facades\Hash;

public function yourControllerMethod(Request $request)
{
    // Verify CSRF token manually
    if (Hash::check($request->header('X-CSRF-TOKEN'), csrf_token())) {
        // CSRF token is valid
        // Your logic here
    } else {
        // Invalid CSRF token
        abort(419);
    }
}

Note

  • Ensure that your Ajax requests are being sent as POST requests since CSRF protection is applied to non-GET requests.

  • Keep the CSRF token secure and do not expose it to the public.

By implementing these steps, you can resolve the "CSRF Token Mismatch for Ajax POST Request" issue in Laravel.