我正在创建一个允许用户创建测验的应用程序。我希望用户将他们喜欢的问题和答案添加到数据库中。我想要一个表单提交一系列问题和答案(1个问题+ 4个可能的答案)。
我的控制器中的foreach
会产生错误。我检查了提交时发送内容的内容,它只是表单中输入的最后一组值。谁能指出我正确的方向做什么?
PS。如果我删除了foreach
,我可以存储插入到表单中的最后一组值。
以下是包含表格
的视图 <form method="POST" action="{{ route('questions.store') }}">
<div ng-controller = "add-forms">
<fieldset data-ng-repeat="question in questions">
<button class="btn btn-info btn-sm" ng-show="$last" ng-click="removeQuestion()"><span class="glyphicon glyphicon-minus" ></span></button>
<br /><br />
<div class="form-group">
<label name="question">Question:</label>
<input id="question" ng-model="question.question" name="question" class="form-control">
</div>
<div class="form-group">
<label name="answer">Correct Answer:</label>
<input id="answer1" ng-model="question.answer1" name="answer1" rows="10" class="form-control">
</div>
<div class="form-group">
<label name="answer">Wrong Answer 1:</label>
<input id="answer2" ng-model="question.answer2" name="answer2" rows="10" class="form-control">
</div>
<div class="form-group">
<label name="answer">Wrong Answer 2:</label>
<input id="answer3" ng-model="question.answer3" name="answer3" rows="10" class="form-control">
</div>
<div class="form-group">
<label name="answer">Wrong Answer 3:</label>
<input id="answer4" ng-model="question.answer4" name="answer4" rows="10" class="form-control">
</div>
</fieldset>
<button class="btn btn-info btn-sm" onclick="return false" ng-click="addQuestion()" > <span class="glyphicon glyphicon-plus" > </span> </button>
<br /><br />
</div>
<input type="submit" value="Create Quiz" class="btn btn-success btn-lg btn-block">
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
AngularJS代码,可以动态地向表单添加或删除更多字段,如下所示:
prequiz_module.controller('add-forms', function($scope){
$scope.questions = [{id: 'question1'}];
$scope.addQuestion= function(){
var newQuestion = $scope.questions.length + 1;
$scope.questions.push({'id':'choice'+newQuestion});
};
$scope.removeQuestion = function(){
var lastQuestion = $scope.questions.length-1;
$scope.questions.splice(lastQuestion);
};});
存储表单输入的控制器
public function store(Request $request)
{
foreach ($request as $q){
$this->validate($q, array(
'question'=> 'required',
'answer1' => 'required',
'answer2' => 'required',
'answer3' => 'required',
'answer4' => 'required'
));
$questions = new Questions;
$questions ->quizID=Session::get('quizID');
$questions ->question=$q->question;
$questions->answer1=$q->answer1;
$questions->answer2=$q->answer2;
$questions->answer3=$q->answer3;
$questions ->answer4=$q->answer4;
$questions->save();
}
return redirect()->route('questions.show','testing');
}
答案 0 :(得分:1)
扩展我的评论。
您的重复字段具有相同的name=""
。
如果您发布任意数量的字段,如果每个字段都具有相同的name=""
,则只有最后一个字段进入。您可以将其更改为name="question[]"
,以便将它们作为数组发送到相应的索引。
如果对每个输入执行此操作,则应获得5个数组(question[]
,answer1[]
等),这些数组应具有匹配的索引。因此answer1[0]
属于question[0]
。
答案 1 :(得分:0)
如果您遇到问题,我会使用dd();
确认变量的值。首先,我会将您的foreach
电话更新为:
foreach ($request->all() as $q) {
根据the documentation,all()
方法可以访问请求中的值数组。