| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace Longyi\FrontMenu\Repositories;
- use Illuminate\Support\Facades\Cache;
- use Longyi\FrontMenu\Models\FrontMenuItem;
- use Webkul\Core\Eloquent\Repository;
- class FrontMenuItemRepository extends Repository
- {
- public function model()
- {
- return FrontMenuItem::class;
- }
- /**
- * Build a hierarchical tree (up to three levels) of all menu items.
- */
- public function getMenuTree(bool $onlyEnabled = false)
- {
- $query = $this->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');
- }
- }
|