I have a problem replicating one of my models with all relationships.
The structure of the database is as follows:
Table1: products
id
name
Table2: product_options
id
product_id
option
Table3: categories
id
name
Pivot table: product_categories
product_id
category_id
Relations:
- product hasMany product_options
- the product belongs to any category (trough product_categories)
I would like to clone a product with all relationships. My code is currently located here:
$product = Product::with('options')->find($id);
$new_product = $product->replicate();
$new_product->push();
foreach($product->options as $option){
$new_option = $option->replicate();
$new_option->product_id = $new_product->id;
$new_option->push();
}
But this does not work (the relationship is not cloned - currently I was just trying to clone product_options).
source
share