Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MichielElswood's avatar

Kalnoy/nestedset Children issue

I've made a nested database setup. But even when a page has children (page has parent_id), the children() relation stays empty.

PageController:

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(request()->input('navigationMenuId') !== null)
            $navigationMenuId = request()->input('navigationMenuId');
        else
            $navigationMenuId = 2;

        $navigationMenu = $this->getNavigationMenu($navigationMenuId);
        $navigationMenuPages = $this->getNavigationMenuPages($navigationMenu);

        dd($this->getNavigationMenuPages($navigationMenu)); // To get the pages back for debugging.

        return view('admin.modules.page.index', compact('navigationMenu', 'navigationMenuPages'));
    }

    // Get navigation menu.
    protected function getNavigationMenu($navigationMenuId)
    {
        return NavigationMenu::where('id', $navigationMenuId)->firstOrFail();
    }

    protected function getNavigationMenuPages(NavigationMenu $navigationMenu)
    {
        return Page::whereHas('navigation_menus', function($query) use ($navigationMenu) {
            $query->whereId($navigationMenu->id);
        })->get()->toTree();
    }

Page.php

    public function navigation_menus()
    {
        return $this->belongsToMany(\App\Models\NavigationMenu::class);
    }

I made a pivot table where the page and menu come together. If wanted, I can provide that too.

Point is: I have a page with ID 2. That's the parent. Pages with the ID 3,4,5 have a Parent_id. Which is 2.

The Dump.

Kalnoy\Nestedset\Collection {#1822 ▼
  #items: array:3 [▼
    0 => App\Models\Page {#1935 ▼
      #connection: "mysql"
      #table: "pages"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:19 [▶]
      #original: array:19 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:2 [▼
        "parent" => null
        "children" => Illuminate\Database\Eloquent\Collection {#1879 ▼
          #items: []
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
      -roleClass: null
      -permissionClass: null
      +mediaConversions: []
      +mediaCollections: []
      #deletePreservingMedia: false
      #unAttachedMediaLibraryItems: []
      #pending: null
      #moved: false
    }
    1 => App\Models\Page {#1933 ▶}
    2 => App\Models\Page {#1932 ▶}
  ]
}
0 likes
1 reply

Please or to participate in this conversation.