model->newQuery(); if ($onlyEnabled) { $query->where('status', 1); } $items = $query->orderBy('parent_id') ->orderBy('sort_order') ->orderBy('id') ->get(); return collect($this->buildTree($items)); } /** * Get the enabled front menu tree, cached for the frontend / GraphQL. */ public function getEnabledMenuTree() { return Cache::remember('front_menu_tree', 3600, function () { return $this->getMenuTree(true); }); } /** * Recursively build the menu tree. */ protected function buildTree($items, ?int $parentId = null) { $tree = []; foreach ($items as $item) { $itemParentId = $item->parent_id === null ? null : (int) $item->parent_id; if ($itemParentId === $parentId) { $children = $this->buildTree($items, (int) $item->id); $item->setRelation('children', collect($children)); $tree[] = $item; } } return $tree; } /** * Clear the front menu cache. */ public function clearCache(): void { Cache::forget('front_menu_tree'); Cache::forget('front_menu_items'); } }