How to update a table with an array in the Laravel?

Asked

Viewed 110 times

0

CONTROLLER CODE

    $form_data =  array(

                   'numdoc' => $request->numdoc,
                   'data_emissao' => $date_emissao,
                   'data_debito' =>  $date_debito,
                   'cliente_id' => $request->cliente_id,
                   'devedor_id' => $request->devedor_id,
                   'valor' => $request->valor,
                   'user_id' => Auth::id(),
                    'meses_atraso'  => $request->meses_atraso,
                    'multa' => $request->multa,
                    'valor_recebido'  => $request->valor_recebido,

    );


Divida::update($form_data);

Error: Non-static method Illuminate Database Eloquent Model::save() should not be called statically

  • What is the key field of the table?

  • In the table is as id

2 answers

1

One option would be to use mass association of the Laravel. This way it is not necessary to "set" all fields one by one.

// Pega todos os campos da request
$formData = $request->all();  

// Adiciona o campo user_id
$formData['user_id'] Auth::id();

// Criar
Divida::create($formData);

// Atualizar
$divida = Divida::find(1);
$divida->fill($formData)->save();

1


I advise to study a little the documentation of the Eloquent of the Laravel. https://laravel.com/docs/5.8/eloquent

To create a record use the create method();

$form_data =  array(

                   'numdoc' => $request->numdoc,
                   'data_emissao' => $date_emissao,
                   'data_debito' =>  $date_debito,
                   'cliente_id' => $request->cliente_id,
                   'devedor_id' => $request->devedor_id,
                   'valor' => $request->valor,
                   'user_id' => Auth::id(),
                    'meses_atraso'  => $request->meses_atraso,
                    'multa' => $request->multa,
                    'valor_recebido'  => $request->valor_recebido,

    );


Divida::create($form_data);

You can use update if you already have a template instance.

  //Pesquisa de devolve o Model com o Id = 1 e atualiza o campo valor_recebido

  Divida::find(1)->update(['valor_recebido' => $request->valor_recebido]);

Browser other questions tagged

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