FormRequest.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Http\Requests;
  3. use Illuminate\Contracts\Validation\Validator;
  4. class FormRequest extends \Illuminate\Foundation\Http\FormRequest
  5. {
  6. /**
  7. * 是否把数组字段中元素的错误, 合并到数组字段的错误中,
  8. * 合并之后, 不会出现 field.* 之类的错误, 全部显示在 field 字段中
  9. *
  10. * @var bool
  11. */
  12. protected $mergeArrayError = true;
  13. protected function failedValidation(Validator $validator)
  14. {
  15. $this->mergeArrayError($validator);
  16. parent::failedValidation($validator);
  17. }
  18. /**
  19. * 合并数组字段中元素的错误, 到数组字段的错误中
  20. *
  21. * @param Validator $validator
  22. */
  23. protected function mergeArrayError(Validator $validator)
  24. {
  25. if (!$this->mergeArrayError) {
  26. return;
  27. }
  28. $msgBag = $validator->errors();
  29. foreach ($msgBag->messages() as $field => $errors) {
  30. // 取出第一个 . 号前面的, 作为字段名,
  31. // 例如 http_method.0 --> http_method
  32. // some.0.nested --> some
  33. $dotPos = strpos($field, '.');
  34. if ($dotPos === false) {
  35. continue;
  36. }
  37. $targetField = substr($field, 0, $dotPos);
  38. foreach ($errors as $i) {
  39. $msgBag->add($targetField, $i);
  40. }
  41. }
  42. }
  43. }