RequestApiFormValidation.php 751 B

12345678910111213141516171819202122232425262728
  1. <?php
  2. namespace App\Traits;
  3. use Illuminate\Contracts\Validation\Validator;
  4. use Illuminate\Validation\ValidationException;
  5. use Symfony\Component\HttpFoundation\Response;
  6. trait RequestApiFormValidation
  7. {
  8. // 重写ajax请求验证错误响应格式(防止验证422报错)
  9. protected function failedValidation(Validator $validator)
  10. {
  11. // 此处自定义表单验证错误信息
  12. $data = [
  13. 'code' => 200,
  14. 'success' => false,
  15. 'errors' => $validator->errors()
  16. ];
  17. $response = new Response(json_encode($data));
  18. throw (new ValidationException($validator, $response))
  19. ->errorBag($this->errorBag)
  20. ->redirectTo($this->getRedirectUrl());
  21. }
  22. }