I’m trying to display the options for the questions. i have the problem that when im doing it this way:
@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
i can check all radio buttons at the same time but if i put there a name for the radiobutton i can check only one of the options for the whole questions.. i think there’s something strange with the foreach loop..
Info: the table “questions” has the following rows: id, category_id, question_text, correct_answer, option_text (this is a json-field that is casted to an array)
Code from Controller:
public function store(Request $request, Category $category){ if($request->categoryTest == $category->name){ $questions = $category->question()->inRandomOrder()->get(); return view('user.test', compact('questions', 'category')); } }
do you have an idea how to fix this? thank you!
Advertisement
Answer
Try this:
@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) @php $q = 1+$key @endphp <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 name="radio-{{$q}}" type="radio">{{$option}} @endforeach </div> @endforeach <div class="form-group"> <input type="submit" class="btn btn-primary"> </div> </form> </div> </div> @endsection