You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 7集成jsTree:如何将分类树数据转为jsTree格式?

Hey there! Let's tackle converting your flat category list into the nested structure jsTree needs. The key issue here is that your current getCategoriesTree method outputs a flat array, but jsTree expects a hierarchical structure where each node has its own children array for subcategories.

First, let's recall that the toTree() method from kalnoy/nestedset already returns your categories in a nested Eloquent collection—each category has a children property holding its subcategories. We can leverage this directly to build the jsTree format.

Step 1: Rewrite the getCategoriesTree method

Replace your current flat array generator with a recursive function that builds nested nodes:

private function getCategoriesTree($nodes): array {
    $tree = [];

    foreach ($nodes as $category) {
        // Build the base node structure jsTree expects
        $node = [
            'id' => $category->id,
            'text' => $category->category_name, // jsTree uses 'text' for display
            // Optional: Add state settings (expand/collapse, selection)
            'state' => [
                'opened' => false, // Default to collapsed
                'selected' => false
            ],
            // Recursively add child nodes
            'children' => $this->getCategoriesTree($category->children)
        ];

        // Optional: Customize based on your category properties
        if ($category->enable == 1) {
            $node['icon'] = 'fa fa-check-circle'; // Use FontAwesome icon if you want
        }

        $tree[] = $node;
    }

    return $tree;
}

Step 2: Return proper JSON response

Update your controller method to return JSON (jsTree needs this format):

public function categoryTree(CategoryRepositoryInterface $categoryRepository, Request $request) {
    $nodes = $this->getCategoriesTree($categoryRepository->getTree());
    return response()->json($nodes); // Return JSON instead of raw array
}

Step 3: Frontend jsTree setup

Make sure your frontend code correctly fetches this data. Here's a basic example:

$(document).ready(function() {
    $('#category-tree').jstree({
        'core': {
            'data': {
                'url': '/path-to-your-category-tree-endpoint', // Replace with your actual route
                'dataType': 'json'
            },
            'check_callback': true // Enable if you need to modify the tree (add/edit nodes)
        },
        // Optional: Add plugins like context menu, drag & drop
        'plugins': ['contextmenu', 'dnd']
    });
});

Quick Notes:

  • If you still want to keep the prefix (like - Category for subcategories) in the display text, just update the text line to:
    'text' => str_repeat('-', $category->depth) . ' ' . $category->category_name,
    
    The depth property is provided by kalnoy/nestedset, so you don't need to track the prefix manually.
  • Double-check your Category model uses the NodeTrait from kalnoy/nestedset:
    use Kalnoy\Nestedset\NodeTrait;
    
    class Category extends Model {
        use NodeTrait;
    
        // Your model properties and methods here
    }
    

This should give you the exact nested structure jsTree requires, with parent-child relationships properly represented.

内容的提问来源于stack exchange,提问作者trelloka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:17:48