Skip to content
Advertisement

Checking if there is any validation error when using custom form request class

I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

public function store(CustomFormRequest $request)
{
  //
}

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don’t want that. Instead, inside my controller’s method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}

Could you please help ? Thanks in advance.

Advertisement

Answer

The easiest way to do this would be to override the response() method for the Form Request class.

To do this you can simply add something like the following to your class:

public function response(array $errors)
{
    if ($this->expectsJson()) {
        return new JsonResponse(['status' => 2, 'msg' => $errors], 422);
    }

    return parent::response($errors);
}

Don’t for get to import IlluminateHttpJsonResponse

Hope this helps!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement