You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel在线测验系统后续题目与选项不匹配问题技术求助

问题排查与解决方案

核心问题定位

这种第一题正常、后续题目与选项完全错位的情况,几乎都是视图循环时选项未与当前问题绑定关联,或是后端传递的题目-选项数据结构错误,导致选项被全局复用、遍历错位。

针对性排查与修复

1. 检查mount()方法的数据组装逻辑

必须确保每个题目对象携带自身专属的选项集合,而非所有题目共用同一组选项:

// 错误写法:所有题目共享全局选项数组
$questions = Question::all();
$options = Option::all();
return compact('questions', 'options');

// 正确写法:预加载每个题目对应的关联选项
$questions = Question::with('options')->get();
return compact('questions');

2. 修正视图的循环绑定逻辑

遍历选项时,必须基于当前问题的options关联属性,而非全局选项集合:

{{-- 错误写法:遍历全局$options,导致选项错位 --}}
@foreach($questions as $question)
    <div class="question-item">
        <h4>{{ $question->title }}</h4>
        @foreach($options as $option)
            <label><input type="radio" name="ans[{{ $question->id }}]" value="{{ $option->id }}"> {{ $option->content }}</label>
        @endforeach
    </div>
@endforeach

{{-- 正确写法:遍历当前问题的专属选项 --}}
@foreach($questions as $question)
    <div class="question-item">
        <h4>{{ $question->title }}</h4>
        @foreach($question->options as $option)
            <label><input type="radio" name="ans[{{ $question->id }}]" value="{{ $option->id }}"> {{ $option->content }}</label>
        @endforeach
    </div>
@endforeach

3. 强化submitQuiz方法的合法性校验

提交时验证选项是否属于对应题目,避免非法数据干扰:

public function submitQuiz(Request $request)
{
    $submittedAnswers = $request->input('ans');
    
    foreach($submittedAnswers as $questionId => $optionId) {
        // 验证选项是否归属于当前题目
        $isValid = Option::where('question_id', $questionId)->where('id', $optionId)->exists();
        if(!$isValid) {
            // 处理非法提交逻辑(如返回错误提示)
            return back()->withErrors('提交数据异常,请重试');
        }
        // 后续评分/存储逻辑
    }
}

额外验证点

  • 检查数据库options表的question_id字段,确保所有选项都正确关联到对应题目ID,无填错、重复情况。
  • 若使用前端框架配合Laravel,确认前端循环时每个题目绑定的是自身独立的选项数组,而非全局共享数组。

内容的提问来源于stack exchange,提问作者Dahlanチャネル

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:35:05