PHP Geek PHP Geek - 3 months ago 43
Ajax Question

Jquery validation for duplicate email using laravel

Hi I am using laravel code to check the email is unique or not and at the front end i am using jquery as follows:

blade.php page
user_email: {
required: true,
email: true,
remote: {
url: base_url + "/validate_email",
type: "post"
}
},


and on post i used the following method validation_email in controller:

function validate_email(Request $request) {
if ($request->input('user_email') !== '') {
if ($request->input('user_email')) {
$rule = array('user_email' => 'Required|email|unique:users');
$validator = Validator::make($request->all(), $rule);
}
if (!$validator->fails()) {
die('true');
}
}
die('false');
}


But when I fill the email and it validate it shows an error as CsrftokenMismatch Exception. When i disable the csrf token then csrf token then code is working otherwise it throws an exception.
Please suggest me some solution for this.. Thank You

Answer

Pass the token along in your Request in your blade.

remote: {
    url: base_url + "/validate_email",
    type: "post"
    data: {
      _token: function() {
        return "{{csrf_token()}}"
      }
    }
  }