In Laravel, I have a table which contains id, parent_id, slug (Self-referring),
When I have an ID, I need to get all its ancestors in a format like this (Separated b
If you know how many levels maximum could be nested you can use Eager Loading. Let's say if maximum depth is 3 levels you can do:
$model->with('parent.parent.parent');
You can also use recursion instead of loop.
public function getParentsAttribute()
{
if (!$this->parent) {
return collect([]);
}
return collect($this->parent->parents)->push($this->parent);
}
In case you want to add the first one object too (self) the full call will be:
$model->parents->push($model)->reverse->implode('attr_name', '/');
Which you can also wrap into attribute
public function getPathAttribute() {
return $model->parents->push($model)->reverse->implode('attr_name', '/');
}
And call like $model->path;