Laravel 和无限类别作为一棵树

Laravel and infinity categories as a tree

如何显示所有分类,有sub,sub,sub(..)分类,我有简单的table:

和我的模特:

class Category extends Model
{
    public $fillable = [
        'parent_id',
        'name',
        'description'
    ];

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id', 'id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }
}

我想得到:

<ul>
  <li>Category
    <ul>
      <li>Category 1.1</li>
      <li>Category 1.2</li>
    </ul>
  </li>
  (...)
</ul>

这种实用方法适用于 n 个类别 n 个 children

首先创建一个局部视图 category.blade.php 文件,该文件将递归调用自身以加载其 children

<li>
       @if ($category->children()->count() > 0 )
           <ul>
               @foreach($category->children as $category)

                       @include('category', $category) //the magic is in here

               @endforeach
           </ul>

       @endif
</li>

然后在主视图中添加此代码以递归方式加载所有 children

  <ul>
        @foreach ($categories as $category)

            @if($category->parent_id == 0 )

                @include('category', $category)

            @endif
        @endforeach

    </ul>