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?
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 Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
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
));
}
Have you tried the bail parameter?
https://laravel.com/docs/5.6/validation
This should only return the first validation error, and if all your rules havethe same validation error message, this would get the desired result.
EDIT: This is for Laravel 5.2 and up.