Search code examples
phplaravellaravel-8has-manybelongs-to

Property [group] does not exist on this collection instance


I have retrieved an instance of a product item at blade, so when I do dd($product), I get this result:

enter image description here

And the Product Model is connected to GroupProduct Model like this:

public function groupproducts()
{
   return $this->hasMany(GroupProduct::class,'product_id','id');
}

So at group_product table, the product has a custom group_id like this:

enter image description here

So when I do dd($product->groupproducts); I get this result properly:

enter image description here

Then at the Model GroupProduct, I've added these two relationships:

public function product()
{
    return $this->belongsTo(Product::class,'product_id','id');
}

public function group()
{
    return $this->belongsTo(Group::class,'group_id','id');
}

Now I need to access the name of the group that comes with the retrieved product_id, but when I try this:

dd($product->groupproducts->group->name);

I get this error:

Property [group] does not exist on this collection instance.

However the relationships seems to be applied and it should be showing the name of group...

So what's going wrong here? How can I fix this issue?


UPDATE #1:

Controller:

public function addAttribute(Product $product)
{
        return view('admin.products.addAttribute', compact('product'));
}

Solution

  • $product->groupproducts is a collection(array) of products. You can do:

    dd($product->groupproducts->first()->group->name);
    

    This will get first element from collection which is instance of Group class.