10 months ago

When validation fails, I get a 422 response but not the errors property

Posted 10 months ago by itsfg

Hello everyone,

I have a controller method that takes a custom Request class. If the validation fails, as expected, I get a 422 response with an errors property containing the errors messages defined by the validation rules :

    "message": "The given data was invalid.",
    "errors": {
        "product_code": [
            "The product code field is required."

Then, inside my method, I create a second rules array, and I validate it like this :

$this->validate($request, ['affair_id' => 'required|exists:affairs,id']);

This time, if the validation fails, this is what I get back :

    "error": {
        "message": "The given data was invalid.",
        "status_code": 422

The errors property is gone, I have a status_code property. And everything is nested in an error object.

Any idea why the 2 responses don't have the same format ?

This is odd, in another controller I have exactly the same system with 2 validations, and I get the errors property (first response format displayed) in both cases.

Thank you for your time

Please sign in or create an account to participate in this conversation.