Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.

Set XSRF(/CSRF) Token Globally or TokenMismatchException in Laravel 5.* (for AJAX)

Very easy (পানির লাহান) 🙂

STEP – 1:

First we have to ad a meta tag (name=”_token”) in header

<meta name=”_token” content=”{{ csrf_token() }}” />

STEP – 2:

Then add below jQuery snippet before the </body> tag. Basically here we setting up the csrf token globally for ajax request. And after this we don’t need to send the csrf token on every ajax call.

$(function () {
// SET UP CSRF TOKEN Globally for Ajax Request
$.ajaxSetup({
headers: {
‘X-XSRF-TOKEN’: $(‘meta[name=”_token”]’).attr(‘content’)
}
});
});

STEP – 3:

And finally we have to add a method on “appHttpMiddlewareVerifyCsrfToken.php” file. So, add the below method on VerifyCsrfToken.php

/**
* Determine if the session and input CSRF tokens match.
*
* @param IlluminateHttpRequest $request
* @return bool
*/
protected function tokensMatch($request)
{
$token = $request->session()->token();

$_token = $request->input(‘_token’);

$header = $request->header(‘X-XSRF-TOKEN’);

return StringUtils::equals($token, $_token) ||
($header && StringUtils::equals($token, $header));
}

Now check and let me know your comments. And I don’t mind, if you want to share this article with your friends/colleagues. Bcoz. Sharing’s Caring.  🙂

2 thoughts on “Set XSRF(/CSRF) Token Globally or TokenMismatchException in Laravel 5.* (for AJAX)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress Social Share Plugin powered by Ultimatelysocial