pluck('id')->each(function (int $businessId) use ($taxonomy, $now) { $createdBy = User::where('business_id', $businessId)->value('id') ?? 1; foreach ($taxonomy as $parentName => $parentData) { $parent = $this->firstOrCreateCategory( $parentName, 0, $parentData['code'] ?? null, $businessId, $createdBy, $now ); foreach ($parentData['children'] as $childName => $childCode) { $this->firstOrCreateCategory( $childName, $parent->id, $childCode, $businessId, $createdBy, $now ); } } }); } private function firstOrCreateCategory( string $name, int $parentId, ?string $shortCode, int $businessId, int $createdBy, $timestamp ): Category { $existing = Category::where('business_id', $businessId) ->where('category_type', 'product') ->where('name', $name) ->first(); if ($existing) { if ($shortCode && empty($existing->short_code)) { $existing->update(['short_code' => $shortCode]); } return $existing; } return Category::create([ 'name' => $name, 'short_code' => $shortCode, 'slug' => $shortCode ? Str::slug($shortCode) : null, 'business_id' => $businessId, 'parent_id' => $parentId, 'created_by' => $createdBy, 'category_type' => 'product', 'created_at' => $timestamp, 'updated_at' => $timestamp, ]); } }