Saving data with relationship (Onetomany) Lavarel 5.1

Asked

Viewed 719 times

1

Good afternoon!

I created an application in Laravel where I need to save the data of a particular product, it has a relationship one to n. I’d like to know the best way to do that. I’m trying the way below but it’s not working, it creates the records of the photos and position but does not pass the 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');
}

3 answers

1


Eduardo, good afternoon to you! Thank you for the reply. Finally the solution was thus:

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

On the controller:

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

No matter how many product_photos you have it works..

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');
}

?>
  • Thank you for the answer. I did this but it didn’t solve the problem, when I give the createMany, the photos data is not saved in it..

0

I do not believe that the createMany function exists in Laravel 5.

I suggest you read the relationship documentation in the official documentation of the.

I indicate the steps below to be done the registration the way you need:

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

2 - loop the received $request->get('photos array')

3 - each interaction of the loop:

3.1 - a Productphoto object should be created

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

3.3 - save to Productphoto object

Browser other questions tagged

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