Loop Laravel making only one Insert in the bank, when it should do several

Asked

Viewed 23 times

-1

I’m not getting enough inserts in the database with a loop. At the time of insert, he only makes one.

public function store(Request $request){
        $contrato = new Contrato();    

        $contrato->cont_aluno                 = $request->aluno_id;
        $contrato->cont_data_entrada          = $request->cont_data_entrada;
        $contrato->cont_curso                 = $request->curso_id;
        $contrato->cont_valor_parcelas        = $request->cont_valor_parcelas;
        $contrato->cont_valor_entrada         = $request->cont_valor_entrada;
        $contrato->cont_data_vencimento       = $request->cont_data_vencimento;
        $contrato->cont_status_pagamento      = 1;
        $contrato->cont_n_parcela             = $request->cont_qtdParcela;;
        $contrato->cont_valor_integral        = $request->cont_valor_integral;
        $contrato->cont_valor_desconto        = $request->cont_valor_desconto;
        $contrato->cont_vDesconto             = $request->cont_vDesconto;
        $contrato->cont_valor_final           = $request->cont_valor_final;
        $contrato->cont_material              = $request->cont_material;
        $contrato->cont_fomraPagamento        = $request->cont_fomraPagamento;
        $contrato->cont_matricula             = $request->cont_matricula;
        $contrato->cont_dataPrimeiroPagamento = $request->cont_dataPrimeiroPagamento;
        $contrato->cont_status_contrato       = 1;
        $contrato->cont_observacoes           = $request->cont_observacoes;

        if($contrato->save()){

            $parcelas = new Parcela();
            
            for ($x = 1; $x <= $request->cont_qtdParcela; $x++){
                var_dump($x);
                $parcelas->contrato_id = $contrato->cont_id;
                $parcelas->num_parcela = $x;
                $parcelas->valor_parcela = $request->cont_valor_parcelas;
                $parcelas->status_pagamento = 1;

                $parcelas->save();
            }

            


            //return redirect('/gerar/contrato')->with('success', 'Sucesso ao gerar o contrato');
        }else{
            //return redirect('/gerar/contrato')->with('error', 'Erro ao gerar o contrato');
        }
    }

After the save should make several installments Inserts, I am passing 4 installments, so I want 4 records in the bank.

1 answer

0

I found the solution, I changed my method.

   for ($x = 1; $x <= $request->cont_qtdParcela; $x++){

                Parcela::insert(['contrato_id'      => $contrato->cont_id
                               , 'num_parcela'      => $x
                               , 'valor_parcela'    => str_replace(',','.', $request->cont_valor_parcelas)
                               , 'status_pagamento' => 1]);
            }

Problem solved.

Browser other questions tagged

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