无限极分类

class CategoryController extends Controller
{
    public function index()
    {
        $rootCats = Category::where('parent_id', null)->get();
        return $this->tree($rootCats);
    }

    private function tree($cats) {
        $tree = [];
        foreach ($cats as $cat) {
            $childrenCats = Category::where('parent_id', $cat->id)->get();
            if ($childrenCats->isNotEmpty()) {
                $cat->children = $this->tree($childrenCats);
            }
            $tree[] = $cat;
        }
        return $tree;
    }
}
原文地址:https://www.cnblogs.com/fenle/p/11623450.html