Saving data with hasMany relationship

4

I'm trying to do an update and three tables related to Laravel, the past data comes from a single view, and the relationships have already been made, it should be the action update of my controller that is not right below.

Update of CorretoresControllers

public function update(Corretor $corretor, Request $request) {
    $corretor->update($request->all());
    return redirect('corretores');
}

Model Corretor

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Endereco;
use App\Contato;
use App\Documento;

class Corretor extends Model {

    protected $fillable = ['nome', 'email'];
    protected $table = 'corretors';

    public function endereco() {
        return $this->hasMany('App\Endereco');
    }

    public function contato() {
        return $this->hasMany('App\Contato');
    }

    public function documento(){
        return $this->hasMany('App\Documento');
    }
}

When a dd($request->all()); returns me the following data:

array:11 [▼
  "_method" => "PUT"
  "_token" => "sWlp1StEgwx7PXZbjo7nV8eYecKpic32E21YeWxA"
  "nome" => "Bruno Neves 1"
  "email" => "[email protected]"
  "logradouro" => "TV DO PARAISO 214"
  "numero" => "10"
  "telefone" => "9632242778"
  "celular1" => "9999-9999"
  "celular2" => "9999-9999"
  "cpf" => "123"
  "rg" => "123"
]

Since a dd($corretor); already returns only this data:

"id" => "13"
    "nome" => "Bruno Santos"
    "email" => "[email protected]"
    "created_at" => "2016-01-26 00:55:11"
    "updated_at" => "2016-02-04 03:14:27"
    
asked by anonymous 04.02.2016 / 18:14

1 answer

2

Whenever you save data in Laravel you need to define in the model the fields that are "fillable", in this case in $fillable .

Add the fields of the table that you want to add to $fillable . I also whenever I change the table and put a new field I forget to change the value of this property.

Saving data in relationships

If you intend to save relationship data, you need to specify this as this is not done automatically.

To save data from a hasMany relationship it is necessary to use the saveMany method.

$documentos = [
   new App\Documento($dadosDocumento)
];

$enderecos = [
   new App\Endereco($dadosEndereco),
];

$contato->fill($dadosContato)->save();

$contato->documentos()->saveMany($documentos);

$contato->enderecos()->saveMany($enderecos);

I separated the data into different variables, such as $dadosEndereco and $dadosContato . I usually use the only method. It can be done simply like this:

$dadosEndereco = $request->only(['logradouro', 'numero'])

The result will be:

['logradouro' => 'Rua T', 'numero' => 116]  
    
04.02.2016 / 18:42