Eloquent Parent-Child relationship on same model
<p>I have a model <code>CourseModule</code>, and each of the items are related to the same model.</p>
<h1>Database Structure:</h1>
<p><a href="https://i.stack.imgur.com/IUCMC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IUCMC.png" alt="enter image description here" /></a></p>
<h1>Relation in Model:</h1>
<pre><code>    public function parent()
    {
        return $this-&gt;belongsTo('App\CourseModule','parent_id')-&gt;where('parent_id',0);
    }

    public function children()
    {
        return $this-&gt;hasMany('App\CourseModule','parent_id');
    }
</code></pre>
<p>I tried the following, but it returns only a single level of relation.</p>
<h1>Tried:</h1>
<pre><code>CourseModule::with('children')-&gt;get();
</code></pre>
<p>I'm trying to create a json output like the following,</p>
<h1>Expected Output:</h1>
<pre><code>[
  {
    &quot;id&quot;: &quot;1&quot;,
    &quot;parent_id&quot;: &quot;0&quot;,
    &quot;course_id&quot;: &quot;2&quot;,
    &quot;name&quot;: &quot;Parent&quot;,
    &quot;description&quot;: &quot;first parent&quot;,
    &quot;order_id&quot;: &quot;1&quot;,
    &quot;created_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
    &quot;updated_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
    &quot;children&quot;: [
      {
        &quot;id&quot;: &quot;2&quot;,
        &quot;parent_id&quot;: &quot;1&quot;,
        &quot;course_id&quot;: &quot;2&quot;,
        &quot;name&quot;: &quot;Child 1&quot;,
        &quot;description&quot;: &quot;child of parent&quot;,
        &quot;order_id&quot;: &quot;2&quot;,
        &quot;created_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
        &quot;updated_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
        &quot;children&quot;: [
          {
            &quot;id&quot;: &quot;3&quot;,
            &quot;parent_id&quot;: &quot;2&quot;,
            &quot;course_id&quot;: &quot;2&quot;,
            &quot;name&quot;: &quot;Child2&quot;,
            &quot;description&quot;: &quot;child of child1&quot;,
            &quot;order_id&quot;: &quot;2&quot;,
            &quot;created_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
            &quot;updated_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
            &quot;children&quot;: [
              {
                &quot;id&quot;: &quot;4&quot;,
                &quot;parent_id&quot;: &quot;3&quot;,
                &quot;course_id&quot;: &quot;2&quot;,
                &quot;name&quot;: &quot;Child 3&quot;,
                &quot;description&quot;: &quot;child of child 2&quot;,
                &quot;order_id&quot;: &quot;2&quot;,
                &quot;created_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
                &quot;updated_at&quot;: &quot;-0001-11-30 00:00:00&quot;,
                &quot;children&quot;: []
              }
            ]
          }
        ]
      }
    ]
  }
]
</code></pre>
<p>I don't understand how to get the inner child objects.</p>