Explanation of the issue: When validating data is in the form of an array object, use a validation form with the rules below.
1 2 3 4 5 6 7 8 9 10 11 12 | public function rules() { return [ 'timestamp' => 'nullable|max:20|date_format:Y/m/d H:i:s', 'count' => 'nullable|integer', 'data' => 'required|array', 'data.*.id' => 'required|max:100', 'data.*.type' => 'required|max:20', 'data.*.name' => 'required|max:100', ] } |
Suppose in the data array, on the 5th object there is a null key name. Instead of returning an error message with the key and value of data.4.name , in laravel 5.7 it will return the value of the data array.
Specifically, you can view that issue here. https://github.com/laravel/ideas/issues/1993 A laravel contributer said that this is not a bug but a feature, so laravel still plays according to this logic, I don’t think so, my clients too , so I fixed it.
We just need to override the invalidJson function in the App Exceptions Handler class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'message' => $exception->getMessage(), 'errors' => $this->transformErrors($e),, ], $exception->status); } private function transformErrors(ValidationException $exception) { $errors = []; foreach ($exception->errors() as $field => $message) { $errors[] = [ 'field' => $field, 'data' => $this->getTrueFieldValue( $exception->validator->attributes(), explode('.', $field) ), 'message' => $message[0], // mình chỉ cần trả 1 message mỗi field, nếu bạn muốn thay đổi hãy ghi đè. ]; } return $errors; } private function getTrueFieldValue($data, $keyPaths) { if (count($keyPaths) == 0) { return $data; } $key = array_shift($keyPaths); return $this->getTrueFieldValue($data[$key] ?? null, $keyPaths); } |