0

I want to insert multiple records in a table at once submit into a database using eloquent laravel, so I have tried hard.

my code on controller

$x = $request->all();
$datas = DataAnak::create($x)->id_anak;

if ($datas != 0) {
    foreach ($datas as $key => $value) {
        $rows = [
            'nama'             => $request->nama_anak[$key],
            'jenis_kelamin'    => $request->gender_anak[$key],
            'tempat_tgl_lahir' => $request->tmt[$key],
            'tgl_baptis'       => $request->baptis_anak[$key],
            'tgl_sidi'         => $request->sidi_anak[$key],
        ];
        DataAnak::insert($rows);
    }
}

my code on blade page

<tr>
    <td><input type="text" class="form-control" name="nama_anak[]"></td>
    <td><input type="text" class="form-control" name="gender_anak[]"></td>
    <td><input type="text" class="form-control" name="tmt[]"></td>
    <td><input type="text" class="form-control" name="baptis_anak[]"></td>
    <td><input type="text" class="form-control" name="sidi_anak[]"></td>
    <td class="text-center">
        <button type="button" class="btn btn-danger row-del"><i class="fas fa-times"></i></button>
    </td>
</tr>
Rwd
  • 34,180
  • 6
  • 64
  • 78

3 Answers3

1

Try this

$datas = $request->all();
$records = [];
foreach ($datas as $key => $value) {
   $records[][$key] = $value;
}

DataAnak::insert($records);
Sumit Kumar
  • 1,855
  • 19
  • 19
1

why are you trying this complex way and that even not the eloquent way to insert data into database. you should do it like below

foreach($request->nama_anak as $key => $value){
    DataAnak::create([
        'nama_anak' => $request->nama_anak[$key],
        'gender_anak' => $request->gender_anak[$key],
        'tmt' => $request->tmt[$key],
        'baptis_anak' => $request->baptis_anak[$key],
        'sidi_anak' => $request->sidi_anak[$key],
    ]);
}

no need to take the inputs into another variable and create, loop, insert separately.

zahid hasan emon
  • 6,023
  • 3
  • 16
  • 28
0

So I think your field is array, you need to loop it like this, and insert them at once:

$datas = $request->all();
$rows = array();

foreach ($datas as $key => $data) {
    foreach($data as $index => $value) {
        if ($key == 'nama_anak')   $rows[$index]['nama'] = $value;
        if ($key == 'gender_anak') $rows[$index]['jenis_kelamin'] = $value;
        if ($key == 'tmt')         $rows[$index]['tempat_tgl_lahir'] = $value;
        if ($key == 'baptis_anak') $rows[$index]['tgl_baptis'] = $value;
        if ($key == 'tgl_sidi')    $rows[$index]['sidi_anak'] = $value;
    }
}
DataAnak::insert($rows);

PS: If you have multiple records, don't insert/create them in loop. It will decrease the performance

TsaiKoga
  • 12,914
  • 2
  • 19
  • 28