Reputation: 8482
I have a many to many relationship in laravel with a pivot object/table. I want to create a copy of one entry in this table, mantaining all the pivot properties (I have extra attributes for the relationship) and creating a new id.
Is it possible with laravel or should I just hack some raw sql into the database?
Upvotes: 5
Views: 3044
Reputation: 3623
In Laravel 5.4, if you want to clone a many-to-many Model, including its relationships and extra attributes in the pivot table, you need to amend the original solution provided in https://stackoverflow.com/a/34032304/309383 like so:
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
// Once the model has been saved with a new ID, we can get its children
foreach ($newModel->getRelations() as $relation => $items) {
foreach ($items as $item) {
// Now we get the extra attributes from the pivot tables, but
// we intentionally leave out the foreignKey, as we already
// have it in the newModel
$extra_attributes = array_except($item->pivot->getAttributes(), $item->pivot->getForeignKey());
$newModel->{$relation}()->attach($item, $extra_attributes);
}
}
Note that this only applies to many-to-many relationships with pivot tables.
Upvotes: 6