From f058491c178d746bde2f2df10efcea1ce9457933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vicky=20J=C3=A1uregui?= Date: Tue, 8 May 2018 17:39:38 -0300 Subject: [PATCH 1/2] #39: Handle API error codes & messages --- app/Http/Requests/FormRequest.php | 57 +++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 app/Http/Requests/FormRequest.php diff --git a/app/Http/Requests/FormRequest.php b/app/Http/Requests/FormRequest.php new file mode 100644 index 000000000000..03109f71c9dd --- /dev/null +++ b/app/Http/Requests/FormRequest.php @@ -0,0 +1,57 @@ +errors()->getMessages(); + $obj = $validator->failed(); + + foreach ($obj as $input => $rules) { + $i = 0; + $fieldErrors = []; + + foreach ($rules as $rule => $ruleInfo) { + $fieldErrors[] = [ + 'code' => 'errors.'.lcfirst(class_basename($rule)), + 'message' => $errors[$input][$i], + ]; + ++$i; + } + + $transformed[] = ["$input" => $fieldErrors]; + } + + return ['errors' => $transformed]; + } + + /** + * @param Validator $validator + */ + protected function failedValidation(Validator $validator) + { + throw new HttpResponseException( + response()->json($this->formatErrors($validator), + JsonResponse::HTTP_UNPROCESSABLE_ENTITY) + ); + } +} From 1053590370a5801754c07a2312d67116e1ba2759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vicky=20J=C3=A1uregui?= Date: Wed, 9 May 2018 09:27:03 -0300 Subject: [PATCH 2/2] Removing unnecessary quotes --- app/Http/Requests/FormRequest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Requests/FormRequest.php b/app/Http/Requests/FormRequest.php index 03109f71c9dd..8f024b3f2020 100644 --- a/app/Http/Requests/FormRequest.php +++ b/app/Http/Requests/FormRequest.php @@ -38,7 +38,7 @@ protected function formatErrors(Validator $validator) ++$i; } - $transformed[] = ["$input" => $fieldErrors]; + $transformed[] = [$input => $fieldErrors]; } return ['errors' => $transformed];