如何访问 Laravel 背包中的 child 菜单项?

How to access child menu items in Backpack for Laravel?

我从 Backpack Add-On 列表中安装了 MenuCRUD:
https://github.com/Laravel-Backpack/MenuCRUD#usage-in-your-template

并且我将示例代码放入我的 blade,但它只显示第一级菜单项,正如预期的那样

这是我使用的代码:

@foreach (\Backpack\MenuCRUD\app\Models\MenuItem::getTree() as $item)
  <a class="text-gray-500 hover:text-gray-500" href="{{$item->url()}}">{{ $item->name }}</a>
@endforeach

现在文档指出我应该使用 $item->children 访问菜单项的 children。我用下面的代码试了一下:

@foreach (\Backpack\MenuCRUD\app\Models\MenuItem::getTree() as $item)
      <a class="text-gray-500 hover:text-gray-500" href="{{$item->url()}}">{{ $item->children->name }}</a>
@endforeach

但它给了我这个错误 Property [name] does not exist on this collection instance. 但是我可以在数组列表中看到 [NAME]

      [ORIGINAL:PROTECTED] => ARRAY
                    (
                        [ID] => 6
                        [NAME] => Testing-Name
                        [TYPE] => INTERNAL_LINK
                        [LINK] => /TEST/LINK1
                        [PAGE_ID] => 
                        [PARENT_ID] => 2
                        [LFT] => 
                        [RGT] => 
                        [DEPTH] => 
                        [CREATED_AT] => 2021-11-06 10:20:20
                        [UPDATED_AT] => 2021-11-06 10:20:20
                        [DELETED_AT] => 
                    )

上面的调试调用结束了:

@foreach (\Backpack\MenuCRUD\app\Models\MenuItem::getTree() as $item)
   {{print_r($item->children)}}
@endforeach

如何调用 children?

如果你看一下 https://github.com/Laravel-Backpack/MenuCRUD/blob/b4a64a454985f8203efa166a2d5dfebc304d2a48/src/app/Models/MenuItem.php#L34

您调用的方法 returns 菜单项的集合。每个菜单项都有一个 children 的数组。这就是您的调试信息实际显示的内容。

所以你应该这样做:

@foreach (\Backpack\MenuCRUD\app\Models\MenuItem::getTree() as $parent)

    @foreach ($parent->children as $child)

    @endforeach     

@endforeach

这是与标准背包基本主题兼容的代码。

请注意,单击父项会切换子项的可见性。如果父级有 url,则不会链接。

@foreach (\App\Models\MenuItem::getTree(); as $item)
    @if($item->children->count() == 0)
        <li class="nav-item">
            <a class="nav-link" href="{{$item->url()}}">
                {{ $item->name }}
            </a>
        </li>
    @else
        <li class="nav-item nav-dropdown">
            <a class="nav-link nav-dropdown-toggle" href="#">
                {{ $item->name }}
            </a>
            <ul class="nav-dropdown-items">
                @foreach($item->children as $child)
                    <li class="nav-item"><a class="nav-link" href="{{ $child->url() }}">
                        <i class=""></i> {{ $child->name }}</a></li>
                @endforeach
            </ul>
        </li>
    @endif
@endforeach