0

I have a form that user can insert multiple data into database. Here is the form look likeform for input data

On my blade view file, I write something like this

<div class="mb-3 table-responsive">
 <table class="table table-striped" id="program_details">
  <thead>
   <tr>
    <th scope="col">Umur</th>
    <th scope="col">Detail Program</th>
    <th scope="col"> </th>
   </tr>
  </thead>

  <tbody>
   <tr>
    <td>
     <input type="number" class="form-control" id="umur" name="umur[]" value="{{ old('umur') }}" required>
    </td>
    <td>
     <textArea class="form-control" id="detail_program" name="detail_program[]" style="height: 100px;" required>{{ old('detail_program') }}</textArea>
    </td>
    <td>
     <button type="button" class="btn btn-success" onclick="addRow()">Add</button>
    </td>
   </tr>
  </tbody>
 </table>
</div>

For my controller file, I just do this for now

public function store(Request $request)
{
    dd($request->all());
}

After I run the code, I got the data that I wanted, but I don't know how to insert it into database. Here is what I got from the user input

[ "nama_program" => "wertyuio"
  "umur" => array:3 [
    0 => "4"
    1 => "9"
    2 => "6"
  ]
  "detail_program" => array:3 [
    0 => "dfghjnbvcdrtyui"
    1 => "ertyjnbvcxdty"
    2 => "ertyjnbvcxdrtyu"
  ]
]

Just for the record, that umur and detail_program is belong to another database table named program_details and the nama_program is belong to program_vaksins.

NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
Untitled99
  • 25
  • 1
  • 7
  • 1
    Does this answer your question? [How to insert multiple rows from a single query using eloquent/fluent](https://stackoverflow.com/questions/29723865/how-to-insert-multiple-rows-from-a-single-query-using-eloquent-fluent) – RG Servers Dec 21 '22 at 07:30
  • @KGG it help a little, but not entirely solve my problem. Thank you for the information – Untitled99 Dec 21 '22 at 07:43

1 Answers1

2

This setup is not that good since you are grouping ids with ids and values with values instead of id with values.

Anyways, you want to use nested foreach

foreach($array['umur'] as $umur) {
    foreach($array['detail_program'] as $program) {
        Model::create([
            'umur' => $umur,
            'detail_program' => $program
        ]);
    }
}

EDIT FOR DUPLICATED DATA IN DB

Hmm, not 100% sure but this might work just fine :)

foreach($array['umur'] as $key => $umur) {
    Model::create([
        'umur' => $umur,
        'detail_program' => $array['detail_program'][$key]
    ]);
}
devsead
  • 312
  • 7