Eloquent Parent-Child relationship on same model

You should use with('children') in the children relation
and with('parent') in the parent relations.

For your code to be recursive:

public function parent()
{
    return $this->belongsTo('App\CourseModule','parent_id')->where('parent_id',0)->with('parent');
}

public function children()
{
    return $this->hasMany('App\CourseModule','parent_id')->with('children');
}

Note: Make sure your code has some or the other exit conditions otherwise it will end up in a never ending loop.

Leave a Comment