1 year ago

Updating Pivot Attributes

Posted 1 year ago by elliotk


I have a Cart model and a Product model, which i pivot together through a many to many relationship. On the pivot, I have an additional column, quantity, which stores the quantity of the product added to the cart.

If a user adds the same product again, I want to increment the pivot quantity.

On the Cart model I have the relationship defined properly.

return $this->belongsToMany('App\Product')->withPivot('quantity');

In my CartController, I get the current cart in $cart and I have the incoming product_id in the $request. I loop the current cart items, checking whether the product exists in the cart. If found, I want to increment the current quantity with the additional quantity passed on the request. I've written the below, it doesn't throw any errors, but it's not working.

        foreach ($cart->products as $product) {
            if ($product->id == $request->product_id) {
                $product->pivot->quantity = $product->pivot->quantity + $request->quantity;
                return redirect('/cart');

Can anyone please explain how to update the pivot attributes properly?


Please sign in or create an account to participate in this conversation.