我尝试在数据库中保存所选ckeckbox选项的值。 但我总是得到价值" on"保存在我的数据库中,即使我没有选择任何选项。 这是answercontroller的代码。
public function store(Request $request, Survey $survey)
{
// remove the token
$arr = $request->except('_token');
foreach ($arr as $key => $value) {
$newAnswer = new Answer();
if (! is_array( $value )) {
$newValue = $value['answer'];
} else {
$newValue = json_encode($value['answer']);
}
$newAnswer->answer = $newValue;
$newAnswer->question_id = $key;
$newAnswer->user_id = Auth::id();
$newAnswer->survey_id = $survey->id;
$newAnswer->save();
};
这是观点:
{!! Form::open() !!}
@if($question->question_type === 'text')
{{ Form::text('title')}}
@elseif($question->question_type === 'textarea')
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Provide answer</label>
</div>
</div>
@elseif($question->question_type === 'radio')
@foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="radio" id="{{ $key }}" name="answer"/>
<label for="{{ $key }}">{{ $value }}</label>
</p>
@endforeach
@elseif($question->question_type === 'checkbox')
@foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" />
<label for="{{$key}}">{{ $value }}</label>
</p>
@endforeach
请帮助我,我怎样才能获得该选项的价值。提前谢谢。
答案 0 :(得分:0)
这是因为您没有设置复选框的值和名称
@foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" value="{{ $value }}" name="mycheck[]" />
<label for="{{$key}}">{{ $value }}</label>
</p>
@endforeach