1

I made custom request as following.

class CustomRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
      $rule['name']='required';
      $rule['email'] = 'required|email';
      return $rule;
    }
}

How can I return validation errors in ajax? When I didn't use custom request, I returned errors like this.

public function store(Request $request)
{
   $validation = Validator::make($request->all(), [
      'name'=>'required',
      'email'=>'required|email'
   ]
   if($validation->fails())
   {
      return response()->json([$errors=>$validation->errors()]);
   }
   return response()->json(['status'=>'success']);
}

So here instead of Request, if I use CustomRequest then how can we catch errors?


Another thing. In custom request rule, how can we get request input values?

   public function rules()
    {
      $rule['name']='required';
      if($this->input('phone')) {
        $rule['phone'] = 'integer';
      }
      $rule['email'] = 'required|email';
      return $rule;
    }

$this->input('phone') Is this right? Hope to give me answer to my 2 questions.

1 Answer 1

1

the error will be either in your error call back function or catch callback depends on how you make ajax call.

eg.

$.ajax({
        url: "/test",
        type: "post",
        data: {foo:'test'} ,
        success: function (response) {
            console.log(response);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            var data = jqXHR.responseJSON;
            console.log(data.errors);// this will be the error bag.
        }

for FormRequest I think your code is not correct

public function rules()
{
    return [
        'title' => 'required',
        'body' => 'required',
    ];
}

This will do the validation. You do not really need to access the input value as Laravel does it for you. But for some reason, if you really want it you can always use the global helper function request()->input('title');

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

12 Comments

well, it returns 422 error (Unprocessable Entity) And I think Form validation rule is correct. Because it's same return values.($rule is array), With your simple return array, we can't validate according to input value.
it's 422, because something is wrong, there is no problem with it. you can still access the error message from it. @lovecoding
@lovecoding we can validate input, just $validated = $request->validated(); this will give the validated input data.
@lovecoding the only thing is before it was store(Request $request) now it should be store(CustomRequest $request)
status 422 is from rfc4918
|

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.