BrainyT's avatar

How can I add status to the validation response

I'm using form request for validation on an which automatically returned a json of errors when I have one

{
    "message": "The email address has already been taken.",
    "errors": {
        "email_address": [
            "The email address has already been taken."
        ]
    }
}

How can I add a custom key and value inside this json before the response e.g. "status": false

{
   "status": false,
    "message": "The email address has already been taken.",
    "errors": {
        "email_address": [
            "The email address has already been taken."
        ]
    }
}
0 likes
7 replies
jlrdw's avatar
return Response::json([status' => false]);  // facade used here
1 like
tykus's avatar

Handle the ValidationException yourself:

// app/Exceptions/Handler.php
public function register()
{
    $this->renderable(function (ValidationException $exception) {
        return response()->json([
            'status' => false,
            'message' => $exception->getMessage(),
            'errors' => $exception->errors(),
        ], $exception->status);
    });
}
3 likes
martinbean's avatar

@brainyt Why? If you’re getting a validation error response then the status is clearly “false”. You don’t need to add that in the response body. This is literally what HTTP status codes are for.

If you get a 4XX status code, then you have an error. Laravel returns a 422 status code for validation failures.

1 like
BrainyT's avatar

@martinbean I have tried to explain this to other team members, but still insist I have the status there. Though I have found my way around it. Thanks for always coming for us.

tykus's avatar

@BrainyT I don't disagree with @martinbean - but anyway handling the Validation exception yourself in the App\Exceptions\Handler class (shown above) will allow you to achieve this.

1 like
BrainyT's avatar

@tykus yeah, I currently override the invalidJson method on the Handler to solve the problem

tykus's avatar

@BrainyT that’s the solution to modifying the response to a ValidationException. If you’re all set mark the thread closed 👍

Please or to participate in this conversation.