quantity; switch ($item->purchasable_type) { case Perfume::class: $relation = 'perfumes'; break; case Product::class: $relation = 'products'; break; case Bottle::class: $relation = 'bottles'; break; default: return; } $existing = $outlet->{$relation}() ->where("{$relation}.id", $item->purchasable_id) ->first(); if ($existing) { $currentStock = $existing->pivot->stock ?? 0; $outlet->{$relation}()->updateExistingPivot($item->purchasable_id, [ 'stock' => $currentStock + $quantity, ]); } else { $outlet->{$relation}()->attach($item->purchasable_id, [ 'stock' => $quantity, ]); } } }