Level
,它由许多
Questions
水平
,然后逐一提问。
我使用以下方法:
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;
}
然后我将所有错误分组到一个数组中,如下所示:
$errors = [];
$errors['level'] = $levelError;
$errors['questions'] = $questionsErrors; //$questionErrors is an array of each question errors
然后,为了检查我的数组是否正确,我做了一个
\Log::info($errors)
[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',
)),
),
)
如你所见,我有两个问题有错误。为了把这个还给我的客户,当我做以下事情时
if ( count($errors) > 0 ) {
throw ValidationException::withMessages($errors);
}
有人知道为什么会这样吗?似乎是把错误归为一组。
最后,我将添加整个计算结果的方法:
public function Create($data) {
// Create array to handle all the nested resources
$errors = [];
// Validate that the data array is correct
$levelErrors = $this->ValidateDataAgainstModel($data);
if ( !is_null($levelErrors) ) {
$errors['level'] = $levelErrors;
}
$questionsErrors = [];
foreach($data['questions'] as $questionData) {
/*
* We remove the level_id because we are validating the
* question content
*/
$validationBook = Question::ValidationBook();
unset($validationBook['rules']['level_id']);
$questionErrors = QuestionService::ValidateDataAgainstModel($questionData, $validationBook);
if ( !is_null($questionErrors) ) {
$questionsErrors[$questionData['index']] = $questionErrors;
}
}
if ( count($questionsErrors) > 0 ) {
$errors['questions'] = $questionsErrors;
}
if ( count($errors) > 0 ) {
\Log::info($errors);
throw ValidationException::withMessages($errors);
}
// Create the object
$result = Level::create($data);
return $result;
}
我不知道问题是不是
withErrors
您可以在这里看到的方法实现
ValidationException Source Code