Last active
November 21, 2022 20:07
-
-
Save elinardo10/cc13298d0cbda01af90a73dad21060cf to your computer and use it in GitHub Desktop.
Duplicar Model com relação e relação da relação
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function duplicate(Product $product) | |
{ | |
$this->authorize('duplicateProduct', $product); | |
$newProduct = $product->replicate(); | |
$newProduct->name = $product->name . " [Cópia]"; | |
$newProduct->save(); | |
$product->load('variations.items'); | |
$items = []; | |
foreach ($product->variations as $variation) { | |
$newProduct->variations()->create([ | |
'name' => $variation->name, | |
'limit_min' => $variation->limit_min, | |
'limit_max' => $variation->limit_max, | |
'ranking' => $variation->ranking, | |
]); | |
foreach ($variation->items as $item) { | |
$items[] = [ | |
'key' => $variation->name, | |
'name' => $item->name, | |
'ranking' => $item->ranking, | |
'amount' => $item->amount | |
]; | |
} | |
} | |
$newProduct->load('variations.items'); | |
$itemsCollection = collect($items); | |
foreach ($newProduct->variations as $newVariation) { | |
$itemsToSave = $itemsCollection->where('key', $newVariation->name)->map(function ($item) { | |
return [ | |
'name' => $item['name'], | |
'ranking' => $item['ranking'], | |
'amount' => $item['amount'] | |
]; | |
}); | |
$newVariation->items()->createMany($itemsToSave); | |
} | |
return new ProductResource($newProduct); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment