Update with hasMany relationship for two inputs at the same time in Windows

Asked

Viewed 188 times

0

Well the problem that happens is this, have in my application the phone field that is present in a relationship for personFisica then a person has a hasMany relationship for phones and that in turn has a belongsto for good person so far all right the problem is happening when I will do the since they are two inputs, the view code looks like this:

 @foreach($pessoaFisica->telefones as $tel)
   <div class="col-sm-6">
   <label for="telefone" class="col-sm-6 control-label">Telefone:</label>
   <input type="tel" class="form-control" name="numero[]" id="numero"
   placeholder="Telefone - obrigatório"
   value="{{isset($tel->numero) ? $tel->numero : null}}">
   </div>
 @endforeach

this gives a list of phones as follows:inserir a descrição da imagem aqui

and now I’m trying to take the two fields to edit on the table, and I’m trying to do it this way:

 $dados = $request->input('numero');
 $this->telefone->where('id_pessoa', $idPessoa)->update($dados);

but a mistake is happening. inserir a descrição da imagem aqui I know this is happening because it is a list but I don’t know how to insert it in bulk at once or otherwise.

1 answer

-1

The update method expects an associative array as parameter. Take a look at the documentation: https://laravel.com/docs/5.1/eloquent#basic-updates

So the correct method of doing the update is:

$dados = $request->only('numero'); // array ['numero' => '(number)']
$this->telefone->where('id_pessoa', $idPessoa)->update($dados);

Remembering that to create and update in bulk you need to define in the model.

You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before Doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models Protect Against mass-assignment.

  • But in case the only would not just take the first record?

  • @Andrémartins read the documentation. Only is the request method, where you set that it will return an associative array only with the inputs you set. Read documentation, search for: Mass assign, Input Request and Eloquent Update

Browser other questions tagged

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