So I have data structured like this:
id|parent_id|name
1 |null |foo
2 |1 |bar
3 |2 |baz
So basically foo->bar->ba
I modified tiffanyhwang solution and turned it into a non-static method and included a attribute accessor to make it easier to get results.
public function ancestors()
{
$ancestors = $this->where('id', '=', $this->parent_id)->get();
while ($ancestors->last() && $ancestors->last()->parent_id !== null)
{
$parent = $this->where('id', '=', $ancestors->last()->parent_id)->get();
$ancestors = $ancestors->merge($parent);
}
return $ancestors;
}
and accessor to retrieve a collection of ancestors from model attribute
public function getAncestorsAttribute()
{
return $this->ancestors();
// or like this, if you want it the other way around
// return $this->ancestors()->reverse();
}
so now you can get ancestors like this:
$ancestors = $model->ancestors;
and since its a Collection, you can now easily do for example this:
echo $model->ancestors->implode('title',', ');