Laravel ORM from self referencing table get N level hierarchy JSON

Here’s how you manually retrieve nested relations:

$collection = Model::with('relation1.relation2.relation3')->get();

So in your case it would be:

$surveys = Survey::with('children.children.children')->get();

Obviously this will do the job when the relations are fixed, but it’s not the way to go for a recursive relation to the same table.

Fortunately, you can make such relation recursive, then all you need to retrieve whole tree is this:

$surveys = Survey::with('childrenRecursive');

However, I wouldn’t load parent for each row this way.

So here’s all you need:

// Survey model
// loads only direct children - 1 level
public function children()
{
   return $this->hasMany('Survey', 'parent');
}

// recursive, loads all descendants
public function childrenRecursive()
{
   return $this->children()->with('childrenRecursive');
   // which is equivalent to:
   // return $this->hasMany('Survey', 'parent')->with('childrenRecursive);
}

// parent
public function parent()
{
   return $this->belongsTo('Survey','parent');
}

// all ascendants
public function parentRecursive()
{
   return $this->parent()->with('parentRecursive');
}

EDIT: To get real tree structure, first query must be limited to only root nodes:

$surveys = Survey::with('childrenRecursive')->whereNull('parent')->get();

Leave a Comment