PHP Geek
PHP Geek

Reputation: 4033

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

Upvotes: 3

Views: 3495

Answers (2)

SteD
SteD

Reputation: 14027

Pass the token along in your Request in your blade.

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

Upvotes: 4

Pavul Zavala
Pavul Zavala

Reputation: 425

its easy you CSRF token is in a hide field in your form, i dont remember de id but you can get that value and send it with the email in your post request for example:

required: true,
                                                    email: true,
                                                    remote: {
                                                        url: base_url + "/validate_email",
**YOU CAN ADD THE PARAMS HERE ( _id=" +$("#_id").val() +"),**
                                                        type: "post"
                                                    }

bassically you have add the token who is in your form to your post request, that value is hidden in the form, i hope i explain myself well

Upvotes: 0

Related Questions