Eloquent - relationship pivot table attributes

Hey, I am trying to create simple shopping cart / order module and I've decided to connect orders and products as many to many relationship with pivot table. I've also decided to store the quantity of the ordered item in this pivot table as an extra attribute.

I've checked docs here and it says that I have to add ->withPivot('foo', 'bar'); this method when I am declaring my relationship. I've putted in in both models (Order and Product). So it looks something like this.

Order model:

public function products() {
    return $this->belongsToMany('Product')->withPivot('quantity');

Product model:

public function orders() {
    return $this->belongsToMany('Order')->withPivot('quantity');

My question is how to access this attribute? Docs says that it should be accessed like this:


However $order->pivot is null so when I try to access quantity of non existing object I get an exception. What am I doing wrong and how can I fix it?

Joe5 replied 3 years ago Solution

Found the solution. The problem was that I was trying to access this pivot through order collection. You have to access it through products collection than individual product and than you can do things like this:


Hope it helps someone.

JohnRoofVents replied 1 year ago

This was really helpful! Thank you for posting this.

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us