如何显示带循环的嵌套列表

How to Display Nested List with loop

我正在尝试使用 Laravel 显示嵌套列表。

class Person extends Model
{

    public function father()
    {
        return $this->belongsTo('App\Person', 'father_id');
    } 
}

我可以像下面那样手动访问数据。

user      = \App\Person::find(5);
$this->tree_string .= "<li>";
$this->tree_string .= "<label>".$user->name."</label>";
$user = $user->father;
    $this->tree_string .= "<ul><li>";
    $this->tree_string .= "<label>".$user->name."</label>";
    $user = $user->father;
        $this->tree_string .= "<ul><li>";
        $this->tree_string .= "<label>".$user->name."</label>";
        $this->tree_string .= "</li></ul>";
    $this->tree_string .= "</li></ul>";
$this->tree_string .= "</li>";

但是我如何循环执行此操作直到没有父亲。(如 foreach) 我使用的方法是否正确。

希望你的问题理解正确。 你想在你的 blade 中 foreach(例如),像这样

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

两个选项:

  1. 您可以提前在控制器中准备数据,然后使用 foreach 循环在 Blade 模板中迭代准备好的数据:
@foreach ($users as $user)
    <ul>
        <li>
            <label> {{ $user->name }} </label>
        <li>
    </ul>
@endforeach
  1. 您可以使用 include 标签并递归包含部分,而您当前的用户有父亲:

main-template.blade.php:

@if ($user)
    <ul>
    @include('partials.users', ['user' => $user])
    </ul>
@endif

partials/users.blade.php:

<li><label>{{$user->name}}</label></li>
@if ($user->father)
    <ul>
    @include('partials.users', ['user' => $user->father])
    </ul>
@endif

希望我的回答对您有所帮助!