nanadjei2
1 year ago
126
8
Laravel

Array data not storing in database

Posted 1 year ago by nanadjei2

Am building an app where users can add more input fields and store data those data all at once: test_id, name and score in a table called TestOptions. I get my success message but data not present in database.

This is my view:

   <div class="form-group row">
       <div class="col-md-10">
         <input type="text" class="form-control" name="name[]" id="testOptions" value="">
      </div>
    <div class="col-md-2">
         <input type="text" class="form-control" name="score[]" id="testOptions" value="">
      </div>
  </div>

  <div class="form-group row">
       <div class="col-md-10">
         <input type="text" class="form-control" name="name[]" id="testOptions" value="">
      </div>
    <div class="col-md-2">
         <input type="text" class="form-control" name="score[]" id="testOptions" value="">
      </div>
  </div>

This is my controller:

  public function store(Request $request)
      {
        //dd($request->name, $request->score); 

        $request->validate(Test::$rules);

        $test = Test::create(['title' =>  $request->title, 'question' =>  $request->question]);

        $i = 0;

        foreach ($request->name as $option) {

           \App\TestOption::create([

                'test_id'   =>  $test->id,

                'name'      =>  $option,

                'score'     =>  $request->scores[$i]
                
            ]);

           $i++;
       }
    

        return back()->with('success', 'You have successfully added a new test');

     }

Please sign in or create an account to participate in this conversation.