syncSizes(); $this->syncRecipe(); } protected function syncSizes(): void { $product = $this->record; $sizes = collect($this->data['sizes'] ?? []) ->mapWithKeys(function ($size) { return [ $size['packing_id'] => [ 'description' => $size['description'] ?? null, 'price' => $size['price'], 'sku' => $size['sku'] ?? null, 'gtin' => $size['gtin'] ?? null, ], ]; }) ->toArray(); $product->sizes()->sync($sizes); } protected function syncRecipe(): void { $product = $this->record; $name = $this->data['recipe_name'] ?? null; $spices = $this->data['recipe_spices'] ?? []; if (! $name) { return; } $pivotData = collect($spices)->mapWithKeys(fn ($s) => [ $s['spice_id'] => ['amount_in_percent' => $s['amount_in_percent']], ])->toArray(); if ($product->recipe) { $product->recipe->update(['name' => $name]); $product->recipe->spices()->sync($pivotData); } else { $nextVersion = Recipe::where('product_id', $product->id)->max('version') + 1; $recipe = Recipe::create([ 'name' => $name, 'product_id' => $product->id, 'version' => $nextVersion, ]); $recipe->spices()->sync($pivotData); $product->update(['recipes_id' => $recipe->id]); } } }