如何使用循环显示嵌套列表

i am try to display nested list using Laravel.

class Person extends Model
{

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

I can access Data manually like bellow.

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>";

but how do i do this in loop until there is no father.(like foreach) is the method i am using correct.

Two options:

  1. You can prepare your data in advance in controller and then just iterate over prepared data in Blade template using foreach loop:
@foreach ($users as $user)
    <ul>
        <li>
            <label> {{ $user->name }} </label>
        <li>
    </ul>
@endforeach
  1. You can use include tag and recursive include the partial while your current user has a father:

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

Hope my answer helped!

Hope to understand your question correct. You want to foreach (for example) in your blade, go like this

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