Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert array values into database in laravel

I have 8 different questions that are coming from the database randomly.

Now I want to insert the question_id, user_id and en_answer into en_answers table.

Data was inserted, but here is some error like - the first one is, it's inserting only one-row value and the second one is, the question id is not correct.

I tried something like bellow. Would someone please help to correct the controller method -

In index.blade.php -

<form action="{{ url('en-question-answer') }}" method="POST">
       {{ csrf_field() }}
  <?php 
    $count=1;
  ;?>
  @foreach($equestions as $equestionType)
      @foreach($equestionType as $key => $equestion)
          <p>{{ $equestion->question }}</p>
          <input type="hidden" name="question_id[{{$count}}]" value="{{ $equestion->id }}">
          <label class="radio-inline">
           <input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option1 }}">{{ $equestion->option1 }}
          </label>
           <label class="radio-inline">
           <input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option2 }}">{{ $equestion->option2 }}
           </label>
             <hr>
    <?php $count++; ?>
       @endforeach
   @endforeach      
  <button type="submit" class="btn btn-primary btn-sm pull-right">Submit</button></form>

In my controller-

    public function store(Request $request, User $user){
    $user_id = Sentinel::getUser()->id;

    $answer = new EnAnswer;
    $answer->user_id     = $user_id;

    $data = Input::get();
    for($i = 1; $i < count($data['en_answer']); $i++) {
        $answer->en_answer     = $data['en_answer'][$i];
    }
    for($i = 1; $i < count($data['question_id']); $i++) {
        $answer->question_id     = $data['question_id'][$i];
    }

    //dd($answer);
    //return $answer;
    $answer->save();
    return redirect('submitted')->with('status', 'Your answers successfully submitted');

}
like image 280
Rashed Hasan Avatar asked Jan 06 '18 14:01

Rashed Hasan


Video Answer


1 Answers

You're inserting into DB just one answer, the last one. Also, you can prepare the data and insert all the answers with just one query:

public function store(Request $request)
{
    for ($i = 1; $i < count($request->en_answer); $i++) {
        $answers[] = [
            'user_id' => Sentinel::getUser()->id,
            'en_answer' => $request->en_answer[$i],
            'question_id' => $request->question_id[$i]
        ];
    }
    EnAnswer::insert($answers);
    return redirect('submitted')->with('status', 'Your answers successfully submitted');
}  
like image 87
Alexey Mezenin Avatar answered Sep 21 '22 08:09

Alexey Mezenin