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.

2

1 Answer 1

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]
    ]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

I will try your solution for now. I hope its work for me
Hi man, I just want to let you know that you solution is working, but its inserting each data twice to the database. Do you know how to fix this?
@Untitled99 hello, I am glad it is working, at least partially hehe I have edited my answer, can you please try it?
Thanks for the new answer. I'll try it for now
Hey man, thank you for the new answer. It's work very good. No more duplicate data. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.