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 http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables 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:
$order->pivot->quantity;
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?
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:
$product->pivot->quantity;
Hope it helps someone.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community