I'm trying to make some validations in Laravel. I have a resource with nested resources, so I need to validate many things at once. I have a Level, which is composed by many Questions. So In order to validate them I first validate the Level, and then each question one by one.
I use the following method:
public function ValidateDataAgainstModel($data) {
$book = Level::ValidationBook(); // Or Answer::ValidationBook()
$validator = Validator::make($data,
$book['rules'],
$book['messages']);
if ($validator->fails()) {
return $validator->errors();
}
return null;
}
That method is used in Level and Question, so it is the same. Then I group all errors in a single array like this:
$errors = [];
$errors['level'] = $levelError;
$errors['questions'] = $questionsErrors; //$questionErrors is an array of each question errors
Then to check that my array is correct I make a \Log::info($errors) and get the following result:
[2018-12-12 23:47:12] local.INFO: array (
'level' =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'name' =>
array (
0 => 'Se requiere el nombre del nivel',
),
),
'format' => ':message',
)),
'questions' =>
array (
0 =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'description' =>
array (
0 => 'Se requiere la descripción de la pregunta',
),
),
'format' => ':message',
)),
1 =>
Illuminate\Support\MessageBag::__set_state(array(
'messages' =>
array (
'description' =>
array (
0 => 'Se requiere la descripción de la pregunta',
),
),
'format' => ':message',
)),
),
)
As you can see I have two questions with errors. In order to return this to my client, when I do the following
if ( count($errors) > 0 ) {
throw ValidationException::withMessages($errors);
}
But when the data arrives to my client, the question errors are no complete, instead of get an index with an array of the questions errors, I only got one question error. 
Does anyone knows why this is happening? It seems like is grouping the errors in a single one.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire