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

MahmoudMonem's avatar

best approach to insert multiple radio buttons into database Laravel

Hello guys, my structure is like that. I have the following tables tests -> questions -> options -> responses -> results

My test has many questions -> which has many options > there is no right and wrong so i am doing the following in blade

the final question will look something like this

Question1 : How do you like our restaurant 
Question Options : Great 🔘 🔘🔘 🔘🔘 Bad 
Options weights : Great     5   4   3    2    1    Bad

Question2 : How do you rate our food
Question Options : Great 🔘 🔘🔘 🔘🔘 Bad 
Options weights : Great     5   4   3    2    1    Bad

Question3 : How do you rate our ambience
Question Options : Great 🔘 🔘🔘 🔘🔘 Bad 
Options weights : Great     5   4   3    2    1    Bad

radio buttons like [ agree/disagree style ] each option has a weight and I would like to capture that in the final result as well

@foreach($test->questions as $question ) 
{{$question->title}}
@foreach($questions->options as $option
<div class="custom-control custom-option custom-control-inline mb-2 ">
<input  class="custom-control-input" type="radio" name="choice-{{$question->id}}" id="radio-{{$option->id}}" value="{{$option->weight}}" required>
<label class="custom-option-label rounded-circle" for="radio-{{$option->id}}">
<span class="custom-option-color rounded-circle" >
</span>
</label>
</div>
@endforeach
@endforeach

what I want to achieve 2 things ; 1- insert into responses table all the options selected [ question ids - selected choices id ] 2- insert into results table the user id - test id - sum of the selected options weights

how the code will look like in controller. I can do simple insert and creations but I am really stuck with this for a while. because I need to insert all data

0 likes
14 replies
Tray2's avatar

Simple. you create a table where you have the

  • question_id
  • user_id
  • value

So if the user 1 select bad on question 1

1          1        1

Selects Great on question two

2       1       5
MahmoudMonem's avatar

@Tray2 Thanks Tray for the help, may be I didn't make myself clear enough .. I have no struggles with database tables or how the end result will look like. I want to learn how to do the insertion of all the data . for ex; based on your examples. I know how to insert just question one. but I want to insert multiple questions. maybe I am complicating the process in my head and it's easier than that :D can you show me how the insertion function would look like for the very same two examples you showed.

Tray2's avatar

@MahmoudMonem You insert them using a loop.

Here is an example on how to store a bunch of tracks

  public function storeTracks(array $tracks, ForeignKeyService $foreignKeyService): void
    {
        for ($i = 0; $i < $tracks['track_count']; $i++) {
            $track = [
                'position' => Str::padLeft($tracks['track_positions'][$i], 2, '0'),
                'title' => $tracks['track_titles'][$i],
                'duration' => $tracks['track_durations'][$i],
                'mix' => $tracks['track_mixes'][$i] ?? null,
                'record_id' => $tracks['record_id'],
            ];
            if ($this->isVariousArtists($tracks['record_artist'])) {
                $track['artist_id'] = $foreignKeyService->getArtistId($tracks['track_artists'][$i]);
            }
            Track::create($track);
        }
    }
1 like
Snapey's avatar

by labelling the inputs choice-1. choice-2 etc you are confusing yourself and also making it difficult to parse the id away from the label

Instead name your fields using array syntax, like

<input  class="custom-control-input" type="radio" name="questions[{{$question->id}}]" id="radio-{{question->id}}-{{$option->id}}" value="{{$option->weight}}" required>

now in the controller you can

foreach($request->input('questions') as $key =>$value) {
  here you can save question number and chosen value along with the user id
}
MahmoudMonem's avatar

Hello @Snapey thanks for your help, I have been trying to do the same and managed to get a very few things right, but still can't achieve what I have in mind.. so here is what I want to do and what I have tried so far.

What I am trying to do :

insert into responses table the user choices and their weights 
user_id : 
question_id: 
option_id: [ what he selected ] 
weight: [ the value of selected option ] 

------------------------
create new result table

user_id:
test_id:
result : which is a sum of selected options' weights 

what I tried so far

public function store(Request $request)
    {
        $question_id=  $request->input('question_id');

        $responses = [];
        $total_result =  //  couldn't define this
        foreach ($request->get('questions') as $question_id=> $option_id) {
            $question= question::find($question_id);
            
            $responses[] = [
                'question_id' => $question_id,
                'option_id' => $option_id, // couldn't define this 
            ];


        }
    
    }
Snapey's avatar

@MahmoudMonem do you need to store what option they chose? Just return the weight by setting the weight as the radio value?

MahmoudMonem's avatar

@Snapey

I managed to get everything working except capturing the values of user input ($weight). notice in my code below the $weight I gave it static value 3 to test and the insertion goes fine

I tried these, but none of them worked

 'weight' =>  $request->input('questions'); 
'weight' =>  $request->input('questions',[]); 

when I dd $request->all() .. I can see the weight values in an array "questions". how can I loop it to get each value [ weight ] alone.

Have a look at my code below

        $test_id=  $request->input('test_id');
        $answers = [];  
        foreach ($request->get('questions') as $question_id => $answer_id) {
            $question = Question::find($question_id);
            $option = Option::where('question_id',$question_id)
            ->where('id', $answer_id);
 
            $answers[] = [
                'question_id' => $question_id,
                'option_id' => $answer_id,
                'weight' => 3,
            ];
        }
        //dd($request->all());
        $result = Result::create([
            'test_id' => $test_id,
            'user_id' => \Auth::id(),
            'result' => $test_score
        ]);
        $result->answers()->createMany($answers);
        return back()->with('success');
    }
Snapey's avatar

@MahmoudMonem you didn't answer my question. Why store which option they replied with AND the weight?

MahmoudMonem's avatar

@Snapey oh apologies , I didn't realize it's a question.

I want to store the weight of every option they choose because my end result is about some calculations based on sum of these weights .. for example if the user picked the following weights : 1 4 4 5

The total sum of these weights will be 14 and if a user scored 14 this will mean something.

so in the answers table I will collect all these data.. then in the result page, I will do the calculations of weights and show final results accordingly.

Snapey's avatar

@MahmoudMonem Yes. I know. But you don't need to know that they clicked the 4th radio and this had a weight of 2. Just that they scored 2.

MahmoudMonem's avatar
MahmoudMonem
OP
Best Answer
Level 2

I got it all sorted out thanks @tray2 and @snapey .. here is the full code for future references

blade view

@foreach($test->questions as $question ) 
{{$question->title}}
@foreach($questions->options as $option
<div class="custom-control custom-option custom-control-inline mb-2 ">
<input  class="custom-control-input" type="radio" name="choice-{{$question->id}}" id="radio-{{$option->id}}" value="{{$option->weight}}" required>
<label class="custom-option-label rounded-circle" for="radio-{{$option->id}}">
<span class="custom-option-color rounded-circle" >
</span>
</label>
</div>
@endforeach
@endforeach

Controller

 $test_id=  $request->input('test_id');
 $weight= $request->input('questions', []);
 $test_score = 0;
 $answers = [];  
        foreach ($request->get('questions') as $question_id => $answer_id) {
            $question = Question::find($question_id);
            $option = Option::where('question_id',$question_id)
            ->where('id', $answer_id);
 
            $answers[] = [
                'question_id' => $question_id,
                'option_id' => $answer_id,
                'weight' => $weight[$question_id],
            ];
        }
        //dd($request->all());
        $result = Result::create([
            'test_id' => $test_id,
            'user_id' => \Auth::id(),
            'result' => $test_score
        ]);
        $result->answers()->createMany($answers);
        return back()->with('success');
    }
MahmoudMonem's avatar

@Tray2 .. yes Tray, I just put zero for now will focus on it later .. thank you :)

1 like

Please or to participate in this conversation.