Category : #laravel

Tags : #laravel, #laravel ajax

If you work with Laravel with Ajax, then you will see an error like that laravel csrf token mismatch for ajax post request. We can solve this error in two ways. In this tutorial, we will see how to fix csrf token mismatch in laravel 10 application.

I will show you two solutions for csrf token mismatch error in laravel. If you pass an ajax post request, then by default Laravel expects a csrf token before passing this request to the server. But if you use Ajax get request, then no need to pass csrf token.

To solve this csrf token error while making an ajax request in Laravel, paste this code in you <head></head> tag.

<meta name="csrf-token" content="{{ csrf_token() }}">

 

Now create your Ajax request like that:

$.ajax({
   type: 'post',
   url: "your_url",
   data: data,
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   },
   beforeSend: function(){
     //
   },
   success: function(response){
     //
   },
   complete: function(response){
     //
   }
});

 

You can fix this error by following this way. Just open this below middleware and update it like below:

App\Http\Middleware\VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
        'your_url_you_want_to_avoid_csrf',
    ];
}

 

Conclusion

After completing this laravel csrf token mismatch for ajax post request tutorial, hope now you can solve this error how to fix csrf token mismatch in laravel 10 application. Hope this csrf token mismatch laravel ajax post error tutorial will help you.