Home > OS >  Insert multiple data into database in Laravel
Insert multiple data into database in Laravel

Time:12-23

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 >
 <table  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"  id="umur" name="umur[]" value="{{ old('umur') }}" required>
    </td>
    <td>
     <textArea  id="detail_program" name="detail_program[]" style="height: 100px;" required>{{ old('detail_program') }}</textArea>
    </td>
    <td>
     <button type="button"  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.

CodePudding user response:

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]
    ]);
}
  • Related