44namespace App \Services ;
55
66use App \Models \Product ;
7+ use App \Models \ProductVariant ;
78
89class CartService
910{
10- public function add ($ productId , $ quantity = 1 )
11+ public function add ($ productId , $ quantity = 1 , $ variantId = null )
1112 {
12- $ product = Product::findOrFail ($ productId );
13-
1413 $ cart = session ()->get ('cart ' , []);
1514
16- if (isset ($ cart ['items ' ][$ productId ])) {
17- $ cart ['items ' ][$ productId ]['quantity ' ] += $ quantity ;
15+ // Use unique key for product + variant combo
16+ $ key = $ productId . '_ ' . ($ variantId ?? 'default ' );
17+
18+ $ currentQty = $ cart ['items ' ][$ key ]['quantity ' ] ?? 0 ;
19+ $ newQuantity = $ currentQty + $ quantity ;
20+
21+ $ exceeded = false ;
22+ if ($ newQuantity > 10 ) {
23+ $ newQuantity = 10 ;
24+ $ exceeded = true ;
25+ }
26+
27+ if (isset ($ cart ['items ' ][$ key ])) {
28+ // Update quantity only
29+ $ cart ['items ' ][$ key ]['quantity ' ] = $ newQuantity ;
1830 } else {
19- $ cart ['items ' ][$ productId ] = [
31+ $ product = Product::findOrFail ($ productId );
32+
33+ $ price = $ product ->price ;
34+ $ sku = $ product ->sku ;
35+ $ image = $ product ->image ? asset ($ product ->image ) : 'https://placehold.co/400 ' ;
36+
37+ if ($ variantId ) {
38+ $ variant = ProductVariant::find ($ variantId );
39+ if ($ variant ) {
40+ if ($ variant ->price !== null ) {
41+ $ price = $ variant ->price ;
42+ }
43+ if ($ variant ->sku ) {
44+ $ sku = $ variant ->sku ;
45+ }
46+ if ($ variant ->image ?? false ) {
47+ $ image = asset ($ variant ->image );
48+ }
49+ }
50+ }
51+
52+ $ cart ['items ' ][$ key ] = [
2053 'product_id ' => $ product ->id ,
21- 'title ' => $ product ->title ,
22- 'price ' => $ product ->price ,
23- 'image ' => $ product ->image ? asset ($ product ->image ) : 'https://placehold.co/400 ' ,
24- 'sku ' => $ product ->sku ,
25- 'quantity ' => $ quantity ,
54+ 'variant_id ' => $ variantId ,
55+ 'title ' => $ product ->title ,
56+ 'price ' => $ price ,
57+ 'image ' => $ image ,
58+ 'sku ' => $ sku ,
59+ 'quantity ' => $ newQuantity ,
2660 'attributes ' => [],
2761 ];
2862 }
63+
2964 $ cart = $ this ->updateTotal ($ cart );
3065 session ()->put ('cart ' , $ cart );
66+
67+ return [
68+ 'success ' => !$ exceeded ,
69+ 'message ' => $ exceeded ? 'Maximum quantity for this product is 10. ' : 'Successfully added to cart! ' ,
70+ ];
3171 }
3272
33- public function update ($ productId , $ quantity ){
73+ public function update ($ productId , $ quantity )
74+ {
3475 $ cart = session ()->get ('cart ' );
3576 if (isset ($ cart ['items ' ][$ productId ])) {
3677 $ cart ['items ' ][$ productId ]['quantity ' ] = $ quantity ;
@@ -52,7 +93,8 @@ public function remove($productId)
5293 return $ cart ;
5394 }
5495
55- private function updateTotal ($ cart ){
96+ private function updateTotal ($ cart )
97+ {
5698 $ total = 0 ;
5799 foreach ($ cart ['items ' ] as $ key => $ item ) {
58100 // Skip if key is 'total' itself to avoid issues
0 commit comments