我正在对表单进行验证。我有问题文本的输入,4个输入表单,4个答案,单选按钮和分数的数字输入。
如果我验证这些表单,用户必须为DB创建4个答案,但如果用户只存储3个呢?如何以这种方式进行验证?现在它显示错误,如果我试图存储3个答案,字段是必需的。
我的验证
public function store(Test $test, Request $request)
{
$this->validate($request, [
'text' => 'required',
'point' => 'required',
'correct' => 'required'
]);
$question = new Question();
if($request->has('picture')) {
$question->picture = $request->file('picture')->get();
}
$question->text = $request->input('text');
$question->test_id = $test->id;
$question->save();
foreach ($request->input('answer') as $_index => $_answer)
{
if ( $_answer['text'] ) {
$answer = new Answer();
$answer->text = $_answer['text'];
$answer->point = $_answer['point'];
$answer->correct = ($request->input('correctanswer') == $_index) ? 1 : 0;
$answer->question_id = $question->id;
$answer->save();
}
}
刀片
{!! Form::open(['route' =>
['question.store', $test->id],
'class' => 'form',
'method' => 'post',
'enctype' => 'multipart/form-data'
]
) !!}
<div class="form-group">
{!! Form::label('text', 'Question text') !!}
{!! Form::text('text', '', ['class' => 'form-control', 'placeholder' => '', 'required' => 'required'] ) !!}
</div>
<div class="form-group">
{!! Form::label('picture', 'picture') !!}
{!! Form::file('picture', ['class' => 'form-control']) !!}
</div>
<?php
for($answers_counter = 0; $answers_counter < 4; $answers_counter++) {
?>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Answer{{ $answers_counter + 1 }}</span>
<div class="input-group-text">
<input type="radio" name="correctanswer" id="answer[{{ $answers_counter }}]" value="{{ $answers_counter }}" placeholder="Answer{{ $answers_counter + 1 }}">
</div>
</div>
{!! Form::text('answer[' . $answers_counter . '][text]', '', ['class' => 'form-control']) !!}
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Points</span>
</div>
{!! Form::number('answer[' . $answers_counter . '][point]', '', ['class' => 'form-control']) !!}
</div>
</div>
<?php
}
?>
有人能帮我吗?非常感谢。
如果关闭strictMode,那么sql应该接受空输入,但这只是解决方法。。当您将此粘贴到Model
:的顶部时
protected static $strictMode = false;