I have two arrays I want to validate in my custom Request
:
$rules = [ 'params.words1.*.value' => 'required|string|between:5,50', 'params.words2.*.value' => 'required|string|between:5,50', ];
This returns an error message per each word. But I want a single general message like “Some of the words are invalid”. Is there any Laravel-way to do this?
Advertisement
Answer
You could do this:
$messages = [ 'params.*' => 'Some of the words are invalid.', ];
EDIT:
I think I may have found a solution:
First, make sure you import both Validator and HttpResponseException at the top:
use IlluminateContractsValidationValidator; use IlluminateHttpExceptionsHttpResponseException;
Then, you can override the native failedValidation
method and alter your errors however you want:
protected function failedValidation(Validator $validator) { // Get all the errors thrown $errors = collect($validator->errors()); // Manipulate however you want. I'm just getting the first one here, // but you can use whatever logic fits your needs. $error = $errors->unique()->first(); // Either throw the exception, or return it any other way. throw new HttpResponseException(response( $error, 422 )); }