Home » Jquery » php – How to display departments as nodes in Laravel

php – How to display departments as nodes in Laravel

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a table i db ‘departments’ .I want it do display it with jstree.I have a parent_id,the root node that is 0 and another that is 1 .I have problems in displaying them in a parent and child relationship..Here is my code and what i have tried but the problem is that it is displaying like this:

 - IT Department
     - IT Department
 - IT Department
     - IT Department

and i want it like this

 - IT Department
     - Research and development
 - Finance
     - Product development

    <ul>
    if({{ $department->parent_id }} == 0)
    {

      <li>{{ $department->name }}
        <ul>
          <li id="child_node_1">{{ $department->id }}</li>
          <li >{{ $department->name }}</li>
        </ul>
      </li>    
    }
    if({{ $department->parent_id }} == 1)
    {
      <li>{{ $department->name }}
      <ul>
          <li id="child_node_2">{{ $department->id }}</li>
          <li >{{ $department->name }}</li>
        </ul>
      </li>
    }

    </ul>

enter image description here

How to&Answer:

It sounds like you might want to create a self referential relationship, using laravel’s ORM. Check out the one to one relationship.

Your finished code may look something like this:

Department.php

class Department extends Eloquent {

    public function parents()
    {
        return $this->belongsTo('Department', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('Department', 'parent_id');
    }
}

department.blade.php

<li>{{ $parent->name }}
    <ul>
    @foreach($department->parents as $parent)
        <li id="child_node_1">{{ $parent->id }}</li>
        <li>{{ $parent->name }}</li>
    @endforeach
    </ul>
</li>