Add this to your Category model:
public function getRootCategory()
{
$category = $this;
while ($category->parentCategories) {
$category = $category->parentCategories;
}
return $category;
}
Then do this
$product = Product::with('category.parentCategories')->find(2);
$rootCategory = $product->category->getRootCategory();
dd($rootCategory);
or do this, Recursive Function (Functional Style)
If you prefer recursion
public function getRootCategory()
{
if (!$this->parentCategories) {
return $this;
}
return $this->parentCategories->getRootCategory();
}
But i suspect you may be having a column naming confusion. check your columns again though