Write to two different tables using the same View

2

I'm doing a supplier registration, and I need to record it in one table and its address in another. I use a single view vendors.blade to fill in all the data. How can I separate this data to write them to their respective tables?

Suppliers table:

id          | int
nome        | varchar
endereco_id | int

Address Table:

id          | int
logradouro  | varchar
bairro      | varchar
cep         | int

Controller:

public function store(Request $request)
{
    $input = $request->all();
    Fornecedor::create($input);
    return redirect('fornecedores');
}

Model:

public function endereco() {
    return $this->hasMany('App\Endereco', 'id', 'endereco_id');
}
    
asked by anonymous 07.09.2015 / 00:22

2 answers

2
  

Resolved:   Within the store() method of the Controller provider I have separated the fields for each table, instead of using $request->all() .

SupplierController :

public function store(Request $request)
{
    $endereco = new Endereco();
    $endereco->logradouro = $request->get('logradouro');
    $endereco->numero = $request->get('bairro');
    $endereco->numero = $request->get('cep');
    $endereco->save();
    $endereco_id= $endereco->id;

    $fornecedor = new Fornecedor();
    $fornecedor->cnpj = $request->get('cnpj');
    $fornecedor->razao_social = $request->get('razao_social');
    $fornecedor->endereco_id = $endereco_id;
    $fornecedor->save();

    return redirect('view');
}

I do not know if it's the best way (good practice) to do this, but solved the problem.

    
07.09.2015 / 06:20
1

Speak, my friend, is everything okay? Come on!

Apparently the case is about relationship hasOne ... how come?

Your vendors table works with n: 1 relationship for addresses.

Correcting that in your model you defined as hasMany, that free translation is "contains several". That is, fornecedores contém vários endereços . That according to your schema is not well, in it the provider contains only ONE address, because it works with FK direct to addresses.

The eloquent of the alternatives to work with relationships, in a way practically papaya with sugar.

$fornecedor = new Fornecedor();
$fornecedor->cnpj = $request->get('cnpj');
$fornecedor->razao_social = $request->get('razao_social');
$fornecedor->endereco->logradouro = $request->get('logradouro');
$fornecedor->endereco->bairro = $request->get('bairro');
$fornecedor->endereco->cep = $request->get('cep');
$fornecedor->push();

In this example the "push" will occur. When saving the vendor it will save the address and already make the relation for you.

You can check this method in the manual: link

Remembering that you need to do the ratio of: fornecedores belongsTo enderecos

The push it checks all relation and makes the commands, if you do not like the use of it, you can opt for associate .

Well, one touch doubts!

    
11.09.2015 / 20:30