How to return errors in Laravel Custom Request to Ajax

1.1k views Asked by At

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

There are 1 answers

12
Andy Song On BEST ANSWER

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');