diff --git a/src/Illuminate/Validation/ValidationException.php b/src/Illuminate/Validation/ValidationException.php index 460f959f1fc4..43c0d2c4c9b4 100644 --- a/src/Illuminate/Validation/ValidationException.php +++ b/src/Illuminate/Validation/ValidationException.php @@ -5,6 +5,7 @@ use Exception; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Validator as ValidatorFacade; +use Illuminate\Support\Str; class ValidationException extends Exception { @@ -53,7 +54,7 @@ class ValidationException extends Exception */ public function __construct($validator, $response = null, $errorBag = 'default') { - parent::__construct('The given data was invalid.'); + parent::__construct(static::summarize($validator)); $this->response = $response; $this->errorBag = $errorBag; @@ -77,6 +78,32 @@ public static function withMessages(array $messages) })); } + + /** + * Create a summary error message from the validation errors. + * + * @param \Illuminate\Contracts\Validation\Validator $validator + * + * @return string + */ + protected static function summarize($validator) + { + $messages = $validator->errors()->all(); + + if (!count($messages)) { + return 'The given data was invalid.'; + } + + $message = array_shift($messages); + + if ($additional = count($messages)) { + $pluralized = 1 === $additional ? 'error' : 'errors'; + $message .= " (and $additional more $pluralized)"; + } + + return $message; + } + /** * Get all of the validation error messages. * diff --git a/tests/Validation/ValidationExceptionTest.php b/tests/Validation/ValidationExceptionTest.php new file mode 100755 index 000000000000..d54693c1dea2 --- /dev/null +++ b/tests/Validation/ValidationExceptionTest.php @@ -0,0 +1,54 @@ +getException([], []); + + $this->assertEquals('The given data was invalid.', $exception->getMessage()); + } + + + public function testExceptionSummarizesOneError() + { + $exception = $this->getException([], ['foo' => 'required']); + + $this->assertEquals('validation.required', $exception->getMessage()); + } + + + public function testExceptionSummarizesTwoErrors() + { + $exception = $this->getException([], [ 'foo' => 'required', 'bar' => 'required' ]); + + $this->assertEquals('validation.required (and 1 more error)', $exception->getMessage()); + } + + public function testExceptionSummarizesThreeOrMoreErrors() + { + $exception = $this->getException([], [ + 'foo' => 'required', + 'bar' => 'required', + 'baz' => 'required', + ]); + + $this->assertEquals('validation.required (and 2 more errors)', $exception->getMessage()); + } + + protected function getException($data = [], $rules = []) + { + $translator = new Translator(new ArrayLoader, 'en'); + $validator = new Validator($translator, $data, $rules); + + return new ValidationException($validator); + } +}