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 ruuter answer to use relationships. If you have a parent() belongsTo relationship on the model you can use that one to remove the where clause, see below:
public function parents()
{
$parents = $this->parent()->get();
while ($parents->last() && $parents->last()->parent_id !== null) {
$parent = $parents->last()->parent()->get();
$parents = $parents->merge($parent);
}
return $parents;
}
And then you can access it:
public function allParents(): Collection
{
return $this->parents();
}