Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

naykel's avatar

Selecting single option with createMany()

Select correct answer when creating quiz questions.

I am creating a multiple choice question for a quiz and looking for a way to indicate the correct answer at the same time the question options (answer) are created.

This is easy enough if you use a checkbox because you can just send through an additional is_correct field, however the risk of multiple correct answers being checked is high. Ideally I want to use a radio button but the name attribute needs to be the same and I can not figure ot how to indicate the correct answer in the database.

Controller The question options (answers) are throught the question with the saveMany() method.

<!-- Create question -->
$q = question->create('questions');
<!-- Create many answers (related to question) -->
$q->answers->createMany('answers');

Template

<!-- Create question_options array with checkbox -->
<!-- works but will be possible to check multiple answers -->
<input name="question_options[][answer]" type="text">
<input type="checkbox" name="question_options[0][is_correct]">

<input name="question_options[][answer]" type="text">
<input type="checkbox" name="question_options[1][is_correct]">

or

<!-- Create question_options array with radio -->
<!-- Ideal for single selection but can not get correct when persisting -->

<input name="question_options[][answer]" type="text">
<input type="checkbox" name="answer_id">

<input name="question_options[][answer]" type="text">
<input type="checkbox" name="answer_id">
0 likes
2 replies
Snapey's avatar

why not have one input field for the correct answer, and other fields for the dummy answers?

You can always randomise the order of the answers when you get them for display

naykel's avatar

That will work, and is actually as good idea because if people need to re-sit the test the answers will be in a different postion.

I just trying to make it as felxible as possible so the creator could just move from field to file without much thought.

Another edge case would be if the creator accidentaly got the correct answer mixed up they would need to clear and re-enter both fields rather than just checking the correct box.

Please or to participate in this conversation.