Laravel Eloquent how to get all parents

  eloquent, laravel, parent

I have relation like this:

DB relation

I have a code in my model that retrieves me just one parent:

    public function AllParents()

   {
      return $this->belongsToMany($this, 'parent', 'product_id', 'parent_id')
            ->select('parent', 'name');
   }

I get it in my controller like this:

private function product(Product $product)
{
    return $product->Product()
        ->with('AllParents')
        ->get();
}

Finally I need data like this:

Product1/Product_2/Product_3

I think I need a loop, but how to do it in Eloquent?

Source: Laravel

Leave a Reply