0

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.

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You Veery much. Only thing i have change is @include('partials.users', array('user' => $user->father))
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.