How to insert multiple data at once into the database coming from multiple inputs with the same name?

Asked

Viewed 335 times

0

I am generating lines through javascript for the user to register several information at once in the table. When I send the request, the database only records a record and needs it to take all the filled-in lines and record them in the database. I use Laravel 5.8.

Html code in Blade =>

<form method="POST" action="{{ route('store.peps') }}" class="form">
                    {!! csrf_field() !!}

                    <div class="row mt-3" style="border: 1px solid #FFF;">
                        <div class="col-lg-12 col-md-12 col-sm-12">
                            <div class="row form-group mt-2">
                                <div class="col-lg-12 col-md-12 col-sm-12">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                            <tr>
                                                <th width="05%" class="text-uppercase text-center">remover linha
                                                </th>
                                                <th width="15%" class="text-uppercase text-center">área</th>
                                                <th width="10%" class="text-uppercase text-center">equipamento</th>
                                            </tr>
                                            </thead>
                                            <tbody id="dynamicDiv">
                                            <tr>
                                                <td width="5%" class="text-center">
                                                    <a href="javascript:void(0)" id="removeRow"
                                                       class="btn btn-danger">
                                                        <i class="fas fa-times fa-md"></i></a></td>
                                                <td width="15%" class="text-uppercase text-center">
                                                    <input type="text" name="ds_area[]">
                                                </td>
                                                <td width="10%" class="text-uppercase text-center">
                                                    <input type="text" name="nr_equipamento[]" style="width: 50%;">
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="row mt-2 mb-2">
                                <div class="col-lg-6 col-md-6 col-sm-12 mb-2">
                                    <a href="javascript:void(0)" id="addRow"
                                       class="btn btn-block btn-warning text-uppercase">Adicionar equipamento</a>
                                </div>
                                <div class="col-lg-6 col-md-6 col-sm-12">
                                    <button type="submit" class="btn btn-block btn-success text-uppercase">Salvar
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

javascript =>

$(function () {
        var scntDiv = $("#dynamicDiv");

        $(document).on('click', '#addRow', function () {
            $('<tr>' +
                '<td width="5%" class="text-center">' +
                '<a href="javascript:void(0)" id="removeRow" class="btn btn-danger">' +
                '<i class="fas fa-times fa-md"></i></a>' +
                '</td>' +
                '<td width="15%" class="text-uppercase text-center">' +
                '<input type="text" name="ds_area[]">' +
                '</td>' +
                '<td width="10%" class="text-uppercase text-center">' +
                '<input type="text" name="nr_equipamento[]" style="width: 50%;">' +
                '</td>' +
                '</tr>').appendTo(scntDiv);
            return false;
        });

        $(document).on('click', '#removeRow', function () {
            $(this).parents('tr').remove();
            return false;
        });
    });

Controller Pepcontroller@store =>

public function store(Request $request)
{
    $codMonitoramento = ItensMonitoramento::where('cd_item_monitoramento', '>', 0)->pluck('cd_item_monitoramento')->max() + 1;

    $itensMonitoramentos = new ItensMonitoramento();

    $itensMonitoramentos->cd_item_monitoramento = $codMonitoramento;
    $itensMonitoramentos->ds_area = array($request['ds_area']);
    $itensMonitoramentos->nr_equipamento = array($request['nr_equipamento']);

    $request->flash();
    $itensMonitoramentos->save();

    if($itensMonitoramentos){
        return redirect()->route('list.monitoramentos')->with('success', 'Área e equipamentos cadastrados com sucesso!');
    }else{
        return redirect()->route('list.monitoramentos')->with('error', 'Erro ao cadastrar!');
    }

}

1 answer

0

Like the attribute name of inputs is defined as an array, for each area and equipment dynamically added a new position will be created in the array with the new user-defined values.

Then, in the controller we need to organize the values to use the function createMany.

public function store(Request $request)
{
    $codMonitoramento = ItensMonitoramento::where('cd_item_monitoramento', '>', 0)->pluck('cd_item_monitoramento')->max() + 1;

    $data = []; // Criando um array vazio
    for ($i = 0; $i < count($request['ds_area']); $i++) {
        $data[] = [
            'cd_item_monitoramento' => $codMonitoramento, 
            'ds_area' => $request['ds_area'][$i],
            'nr_equipamento' => $request['nr_equipamento'][$i]
        ]; // Populando cada posição do array com um array contendo os valores a serem persistidos
    }        

    $request->flash();

    try {
         DB::table('tab_itens_monitoramentos')->insert($data);
    } catch (\Exception $e) {
        return redirect()->route('list.monitoramentos')->with('error', $e->getMessage());
    }

    return redirect()->route('list.monitoramentos')->with('success', 'Área e equipamentos cadastrados com sucesso!');
}
  • It didn’t work out, it gives an error saying that the createMany method can’t be used. That’s why I’m not using any relationship type.

  • You can paste the error that is appearing?

  • I got Victor but I had to change his code.

  • I updated the response with the issue you suggested, but it was for the function createMany work well, because I use it without problems in my projects. But each project is a project, right?! I am happy to have helped you out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.