laravel foreach 输入单选按钮显示不正确

我正在尝试显示问题的选项。我有一个问题,当我这样做时:


@section('content')

<div class="card">

  <div class="card-header">Quiz: {{$category->name}}:</div>

  <div class="card-body">

    <form action="#" method="post" class="form-group">

      @csrf

      @foreach($questions as $key => $question)

        <div class="form-group">

          <label for="question">Question {{1+$key}}:</label>

          <p class="card-text">{{$question->question_text}}</p>

          @foreach($question->option_text as $key => $option)

            <input type="radio">{{$option}}

          @endforeach

        </div>

        @endforeach

      <div class="form-group">

        <input type="submit" class="btn btn-primary">

      </div>

    </form>

  </div>

</div>

@endsection

我可以同时检查所有单选按钮,但如果我为单选按钮命名,我只能检查整个问题的一个选项..我认为 foreach 循环有些奇怪..


信息:“问题”表包含以下行:id、category_id、question_text、correct_answer、option_text(这是一个转换为数组的 json 字段)


来自控制器的代码:


public function store(Request $request, Category $category){

  if($request->categoryTest == $category->name){

    $questions = $category->question()->inRandomOrder()->get();

    return view('user.test', compact('questions', 'category'));

  }

}

你知道如何解决这个问题吗?谢谢你!


繁星淼淼
浏览 115回答 2
2回答

繁花如伊

尝试这个:@section('content')<div class="card">&nbsp; <div class="card-header">Quiz: {{$category->name}}:</div>&nbsp; <div class="card-body">&nbsp; &nbsp; <form action="#" method="post" class="form-group">&nbsp; &nbsp; &nbsp; @csrf&nbsp; &nbsp; &nbsp; @foreach($questions as $key => $question)&nbsp; &nbsp; &nbsp; &nbsp; @php&nbsp; &nbsp; &nbsp; &nbsp; $q = 1+$key&nbsp; &nbsp; &nbsp; &nbsp; @endphp&nbsp; &nbsp; &nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label for="question">Question {{1+$key}}:</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p class="card-text">{{$question->question_text}}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @foreach($question->option_text as $key => $option)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input name="radio-{{$q}}" type="radio">{{$option}}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" class="btn btn-primary">&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </form>&nbsp; </div></div>@endsection

万千封印

这似乎是单选按钮的正常行为,当时只有一个是市场。您是否尝试过使用复选框?另外,如果你想将它发送到后端,你需要设置一个名称属性。神奇之处在于:不要使用单数名称,而是将其作为数组放置,以便在您的控制器上获得一个数组。<input&nbsp;type="checkbox"&nbsp;name="question[]"&nbsp;class="btn&nbsp;btn-primary">
打开App,查看更多内容
随时随地看视频慕课网APP