Zoli Zoli - 1 year ago 129
PHP Question

Laravel Eloquent ORM replicate

I have a problem with replicating one of my models with all the relationships.

The database structure is as follows:

Table1: products

Table2: product_options

Table3: categories

Pivot table: product_categories

Relationships are:

  • product hasMany product_options

  • product belongsToMany category (trough product_categories)

I would like to clone a product with all the relationships. Currently here is my code:

$product = Product::with('options')->find($id);
$new_product = $product->replicate();
foreach($product->options as $option){
$new_option = $option->replicate();
$new_option->product_id = $new_product->id;

But this does not works (the relationships are not cloned - currently I just tried to clone the product_options).

Answer Source

This code, worked for me:

$model = User::find($id);


$newModel = $model->replicate();

foreach($model->getRelations() as $relation => $items){
    foreach($items as $item){

Answer from here: Clone an Eloquent object including all relationships?

This answer (same question), also works fine too.

//copy attributes from original model
$newRecord = $original->replicate();
// Reset any fields needed to connect to another parent, etc
$newRecord->some_id = $otherParent->id;
//save model before you recreate relations (so it has an id)
//reset relations on EXISTING MODEL (this way you can control which ones will be loaded
$original->relations = [];
//load relations on EXISTING MODEL
$original->load('somerelationship', 'anotherrelationship');
//re-sync the child relationships
$relations = $original->getRelations();
foreach ($relations as $relation) {
    foreach ($relation as $relationRecord) {
        $newRelationship = $relationRecord->replicate();
        $newRelationship->some_parent_id = $newRecord->id;

From here: Clone an Eloquent object including all relationships?

The code works fine for many to many relationships in my experience.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download