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
- Categoryfor subcategories) in the display text, just update thetextline to:
The'text' => str_repeat('-', $category->depth) . ' ' . $category->category_name,depthproperty is provided by kalnoy/nestedset, so you don't need to track the prefix manually. - Double-check your
Categorymodel uses theNodeTraitfrom 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

