0

I am posting post data from form. I want to validate that array in controller and send a json response to the ajax call. Can you please help me with it.

This is my controller function code where I am submitting form.

public function submit()
{

    $data=array(
        'user_firstname'=>$_POST['user_firstname'],
        'user_lastname'=>$_POST['user_lastname'],
        'user_phone'=>$_POST['user_phone'],
        'email'=>$_POST['user_email'],
        'username'=>$_POST['user_username'],
        'password'=>$_POST['user_password'],

    );
     $validation=validator($_POST);
    if($validation->passes()){

      return "Validation passes";

    }
    else{
        return "Validation failed";
    }
}

 protected function validator(array $data)
{
    return Validator::make($data, [
        'user_firstname' => 'required|string|max:255',
        'user_lastname' => 'required|string|max:255',
        'user_phone' => 'required|string|max:15|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'username' => 'required|string|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

This is my javascript function.

 if(currentTab==2)
{

$.ajax({
      url: "register", 
      type: "post",
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
      success: function(result){
         console.log(result);
        }
    });

}

I want to validate the array and return all the errors in json following is my validator in the same controller.

Please suggest me if there is another way to validate data

Validation is passing every test even with empty array

13
  • Put this code in else part: $error = true; $responsecode = 400; $result["error_message"] = ""; if (sizeof($validator->errors()->getMessages()) > 0){ $messages = $validator->errors()->getMessages(); foreach ($messages as $key => $value) { $result["error_message"] .= $value[0] .' '; } } Commented Mar 16, 2018 at 8:55
  • i dont know whats the problem but its passing every validation test Commented Mar 16, 2018 at 8:55
  • First, do you want to print all errors or anything else? Commented Mar 16, 2018 at 8:56
  • yes i want to print errors Commented Mar 16, 2018 at 8:57
  • Then read my first comment! I have gave code for it! If you don't understand let me know. Commented Mar 16, 2018 at 8:57

1 Answer 1

1

Remove your code and you can try with this code:

public function submit(Request $request)
{
   $error = false; 
   $result = array();
   $responsecode = 200;

   $validator = Validator::make($request, [
            'user_firstname' => 'required|string|max:255',
            'user_lastname' => 'required|string|max:255',
            'user_phone' => 'required|string|max:15|unique:users',
            'email' => 'required|email|unique:users,email',
            'username' => 'required|string|max:255|unique:users,username',
            'password' => 'required|string|min:6|confirmed',
   ]);

   if (!empty($request) && !($validator)){
        try {
            $result = 'Validate!!';     //OR do more your stuff here
        }
        catch(\Exception $e){
            $error = true;
            $responsecode = 500; 
            $result["error_message"] = $e->getMessage();
        }
    } else {
        $error = true;
        $responsecode = 400;
        $result["error_message"] = "";
        if (sizeof($validator->errors()->getMessages()) > 0){
            $messages = $validator->errors()->getMessages();
            foreach ($messages as $key => $value) {
                 $result["error_message"] .= $value[0] .' ';
            }
        }
     }
}

I have used this type of format everytime, try it.

Hope this helps you!!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot man worked like charm thanks a lot seriouly u saved my job
Glad, it helps!! :) This is the format/structure of code to save data and for api with every response code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.