Skip to content

Instantly share code, notes, and snippets.

@elinardo10
Last active November 21, 2022 20:07
Show Gist options
  • Save elinardo10/cc13298d0cbda01af90a73dad21060cf to your computer and use it in GitHub Desktop.
Save elinardo10/cc13298d0cbda01af90a73dad21060cf to your computer and use it in GitHub Desktop.
Duplicar Model com relação e relação da relação
<?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