Customizing Laravel validation JSON message format

By default laravel gives a good enough JSON format for validation errors but what if you want to customize it?

#Original JSON format { "message": "The given data was invalid.", "errors": { "email": [ "Please enter email address." ], "password": [ "Please enter password." ] } }

But for this particular project I decided to change the format to this.

{ "success": false, "success_code": 400, "message": "Please enter email address.", "errors": [ { "field": "email", "message": "Please enter email address." }, { "field": "password", "message": "Please enter password." } ] }

To achieve this I created a ValidationException handler function in app/Exceptions/Handler.php which helped me catch all the exceptions raised as a result of failed validations.

/** * ValidationException * Parameters did not pass validation * * @param ValidationException $exception * @return \Illuminate\Http\Response 400 */ protected function handleValidationException(ValidationException $exception) { $errors = $this->formatErrorBlock($exception->validator); $first = ''; if (!empty($errors) && !empty($errors[0])) $first = $errors[0]['message']; $json = new \stdClass; $json->success = false; $json->success_code = 400; $json->message = $first; $json->errors = $errors; return response()->json($json, 400); }

Next I created formatErrorBlock that would loop through all the default error block created by laravel and format them as required.

public function formatErrorBlock($validator) { $errors = $validator->errors()->toArray(); $return = array(); foreach ($errors as $field => $message) { $r = ['field' => $field]; foreach ($message as $key => $msg) { if ($key) { $r['message'.$key] = $msg; } else { $r['message'] = $msg; } } $return[] = $r; } return $return; }

Notice the if else block in foreach loop. That is because Laravel at times returns multiple errors for a single key hence, I post-fixed the further messages with it’s respective array key.

Follow me
Latest posts by Abhishek Gupta (see all)

One Reply to “Customizing Laravel validation JSON message format”

Leave a Reply