Laravel Eloquent ORM replicate
This code, worked for me:
$model = User::find($id);$model->load('invoices');$newModel = $model->replicate();$newModel->push();foreach($model->getRelations() as $relation => $items){ foreach($items as $item){ unset($item->id); $newModel->{$relation}()->create($item->toArray()); }}
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)$newRecord->push();//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; $newRelationship->push(); }}
From here: Clone an Eloquent object including all relationships?
The code works fine for many to many relationships in my experience.
$product = Product::with('options')->find($id);$new_product = $product->replicate();$new_product->{attribute} = {value};$new_product->push();$new_product->options()->saveMany($product->options);