Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading