Saving data with relationship (OneToMany) Lavarel 5.1

1

Good afternoon!

I created an application in Laravel where I need to save the data of a certain product, it has a one-to-one relationship. I would like to know how best to do this. I am trying the way below but it is not working, it creates the records of the photos and position but does not pass those captured in $ request.

View:

<input type='text' name='photos[0][url]'>
<input type='text' placeholder='Posição de exibição' name='photos[0][position]'>
<br>
<input type='text' name='photos[1][url]'>
<input type='text' placeholder='Posição de exibição' name='photos[1][position]'>

Controller:

$product = Product::create($request->all());            
$photos = $request->get('photos');
$product->photos()->createMany($photos);

Model:

public function photos() {
  return $this->hasMany('Grafica\Model\ProductPhoto');
}
    
asked by anonymous 06.12.2015 / 20:51

3 answers

0

Eduardo, good afternoon! Thanks for the answer.. Finally, the solution was as follows:

<input type='text' name='product_photos[0]['url']>
<input type='text' name='product_photos[0]['position']>

No controller:

$product = Product::create($request->all());
$product->photos()->createMany($request->get('product_photos'));

Regardless of how many product_photos you have, it works.

    
08.01.2016 / 18:12
0
    <?php
/*
O modelo que cede a chave estrangeira que tem o hasmany o que possui a chave da entidade cedente possui belongsTo

Por exemplo:
A tabela pedidos possui a id do produto então no modelo de pedidos haverá.
*/
function produto()
{
    return $this->belongsTo('App\models\Produto');
}
/*
A tabela de produtos cede o id a tabela pedidos então no modelo de produto haverá:
*/
function pedido(){
    return $this->hasMany('App\models\Pedido','id_produto');
}

?>
    
06.12.2015 / 21:43
0

I do not believe the createMany function exists in laravel 5.

I suggest you read the documentation in the official laravel documentation .

I indicate the steps below so that the registration is done the way you need it:

1 - Persist the product in the bank, this way you will have access to the product ID.

2 - you should loop in the received array from $ request-> get ('photos')

3 - each loop interaction:

3.1 - a ProductPhoto object must be created

3.2 - Assign the array values to the attributes of the created object and in the foreignkey field put the product ID created in step 1.

3.3 - perform a save on the ProductPhoto object

    
07.01.2016 / 17:49