[SOLVED] How to insert multiple row from form in laravel 8

Issue

I have a table in a form similar to this:

products comments
product 1 comment 1
product 2 comment 2
  • Only comment field is writable where user can enter a comment regarding each product
  • Products are displayed from database (not in an input element)

I want, when user click on save button, each row is added in database as it is in the form (as pairs [product i, comment i])

I tried

foreach ($request->products as $key=>$product) {
            $saveData = [
                'product' => $request->product[$key],
                'comment' => $request->comment[$key],
            ];
            DB::table('prod_com')->insert($saveData);
        }

in controller and

<form id="regForm" method="post" >
 @csrf
<table>
  <tr>
    <th>Product</th>
    <th>Comment</th>
  </tr>
  @foreach($prdcts as $products)
  <tr>
    <td>{{$products['product']}}</td>
    <td>
      <input type="text" class="form-control" name="coment[]" >
    </td>
  </tr>
</table>

in form but either data isn’t added in database or i get a 405 error Method Not Allowed..

Any help is highly appreciated !

Edit :
Full html form

<form id="regForm" action="{{route('saved')}}" method="post" >
       @csrf    
       <table class="table table-responsive table-condebsed table-hover">
           <thead>
             <tr>
              <th scop="col"> Product </th>
              <th class="col-md-6" scop="col"> Comment </th>
             </tr>
            </thead>
            <tbody>
              @foreach($prdcts as $products)
              <tr>
               <td>{{ $products['product'] }}</td>
               <td>
                 <input type="text" class="form-control" name="coment[]" >
               </td>
              </tr>
             @endforeach
            </tbody>
           </table>
           <br>
           <button type="submit" class="btn btn-sm btn-success">save</button>
</form>

& route :

Route::post('/saved', [App\Http\Controllers\OperatorController::class, 'submitData'])->name('saved');

Solution

Change html code as below

 @foreach($prdcts as $key=>$products)
                    <tr>
                        <td>{{$products['product']}}</td>
                        <td>
                            <input type="hidden" class="form-control" name="product[{{ $key}}][product]" value="{{$products['id']}}">
                            <input type="text" class="form-control" name="product[{{ $key}}][comment]" >
                        </td>
                    </tr>
                @endforeach

then in controller

 DB::table('prod_com')->insert($request->product);

if you get any error then try to print $request like below

dd($request->all());

so you can check data format in the request.If still issue then let me know in the comment

Answered By – John Lobo

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *