Laravel控制器如何让if条件对所有题目记录生效实现答题校验
问题排查
现有代码存在3个核心问题,导致无法适配多题校验:
- 未关联具体题目ID:仅校验提交的答案是否为任意题目的正确答案,没有和用户当前作答的题目绑定,完全无法区分不同题目的正确答案,自然不能支持多题校验
- 查询语法错误:
where('ans',[$request->ans])等值匹配传入了数组参数,逻辑不符合预期,等值匹配应该直接传值,数组匹配需用whereIn方法 - 查询逻辑冗余:使用
get()获取全量匹配集合,仅做判空的场景下用exists()查询性能更高,不需要返回完整的模型数据
修复方案
单题作答场景
首先需要前端提交答案时同时传递2个参数:question_id(当前作答的题目ID)、user_ans(用户选择的答案),控制器修改为如下代码:
public function answerQuestions(Request $request) { // 校验请求参数合法性 $validated = $request->validate([ 'question_id' => 'required|exists:questions,id', 'user_ans' => 'required' ]); // 直接判断对应题目的正确答案是否和用户提交的一致 $isCorrect = Question::where('id', $validated['question_id']) ->where('ans', $validated['user_ans']) ->exists(); if (!$isCorrect) { return back()->withErrors(['fail' => 'Wrong Answer']); } return redirect()->back()->with('success', 'your Answer is Correct'); }
多题批量作答场景
如果需要一次提交多道题的答案,前端按questions[题目ID] = 用户答案的格式传参,示例参数结构:questions[1] = A、questions[2] = C,控制器修改为如下代码:
public function answerQuestions(Request $request) { // 校验参数合法性 $validated = $request->validate([ 'questions' => 'required|array', 'questions.*' => 'required' ]); $correctCount = 0; $wrongQuestionIds = []; // 遍历校验每道题的答案 foreach ($validated['questions'] as $questionId => $userAns) { $isCorrect = Question::where('id', $questionId) ->where('ans', $userAns) ->exists(); $isCorrect ? $correctCount++ : $wrongQuestionIds[] = $questionId; } // 返回结果可根据需求自定义展示逻辑 return back() ->with('success', "Submitted successfully, you got {$correctCount} correct answers") ->with('wrong_question_ids', $wrongQuestionIds); }
内容的提问来源于stack exchange,提问作者M Farhan Shaukat
相关产品推荐
相关产品推荐

