我正在尝试保存每门课程的考试,这是我尝试过的。我得到的错误是找不到错误页面404,并且数据也没有保存在数据库中。
这是我的控制人
public function exam($course_id, Request $id)
{
$course = Course::where('id', $id)->firstOrFail();
$answers = [];
$exam_result = 0;
foreach ($request->get('question') as $question_id => $answer_id) {
$question = ExamQuestion::find($question_id);
$correct_answer = ExamOption::where('exam_questions_id', $question_id)
->where('id', $answer_id)
->where('is_correct', 1)->count() > 0;
$answers[] = [
//this comes from the exam_results_answers
'exam_question_id ' => $question_id,
'exam_option_id' => $answer_id,
'corect' => $correct_answer
];
if ($correct_answer) {
$exam_result += $question->score;
}
}
//this comes from exam result and is correct
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_result
]);
$exam_result->answers()->createMany($answers);
return redirect()->route('learn.show', [$course->curriculum_id, $id])->with('message', 'Test score: ' . $exam_resut);
}
这是刀片
<form action="{{ route('exam.save', [$courses->id]) }}" method="post">
{{ csrf_field() }}
@foreach($courses->exam->question as $question)
<br>{{$loop->iteration}} . {{$question->question}}</b>
</br>
@foreach($question->exam_options as $option)
<input type="radio" name="question[{{ $question->id }}]" value="{{ $option->id }}"/> {{ $option->text }}</br>
@endforeach
<br>
@endforeach
</br>
<input type="submit" value=" Submit results " />
</form>
这是路线
Route::get('/exam/{id}', 'EmployeeCoursesController@view_exam')->name('exam.show');
Route::post('/exam/{id}', 'EmployeeCoursesController@exam')->name('exam.save');
答案 0 :(得分:2)
看一下exam()
函数中的参数,我相信这一行:
$course = Course::where('id', $id)->firstOrFail();
实际上应该是:
$course = Course::where('id', $course_id)->firstOrFail();
firstOrFail()
如果无法从数据库中解析模型,则会抛出404。