Shopping cart laravel

Par Muxxable, il y a 7 ans


Bonjour,

J'essaie de développer un panier sous laravel avec un système d'option. Actuellement tout fonctionne bien, sauf lorsque j'ai des options.

Admetons j'ai un Tshirt taille S à 10€ et j'ajoute le même Tshirt en taille L à 11€, je vais avoir juste la quantité qui change de 1 à 2 au lieu d'avoir 2 lignes dans ma session. Pour le moment j'ai un code qui n'est pas top mais fonctionelle uniquement sans options.

public function add($product, $id, $variant = null) { if($variant){ $stored = ['qty' => 0, 'product' => $product->name, 'price' => $product->price, 'variant' => $variant->name, 'variantPrice' => $variant->price]; if($this->products) { if(array_key_exists($id, $this->products)){ $stored = $this->products[$id]; } } $stored['qty'] ++; $stored['price'] = ($product->price + $variant->price) * $stored['qty']; $this->products[$id] = $stored; $this->totalQty++; $this->totalPrice += $stored['price']; } else{ $stored = ['qty' => 0, 'product' => $product->name, 'price' => $product->price, 'variant' => null, 'variantPrice' => null]; if($this->products) { if(array_key_exists($id, $this->products)){ $stored = $this->products[$id]; } } $stored['qty'] ++; $stored['price'] = $product->price; $this->products[$id] = $stored; $this->totalQty++; $this->totalPrice += $stored['price']; } }

La session actuelle

App\Cart {#307 +products: array:1 [ 1 => array:5 [ "qty" => 2 "product" => "Tshirt" "price" => 10.00 "variant" => "Taille S" "variantPrice" => 1 ] ] if(array_key_exists($id, $this->products)){ $stored = $this->products[$id]; }

Mais comment déterminer que si il y a une variante, il store sur une autre ligne ?

3 réponses

rueduphp, il y a 7 ans

En effet ton problème vient du fait que tu sauvegardes par id produit, et les deux items ont le même id. Tu devrais créer une clé unique du style $id = sha1($product->id . $variant->name . $variant->price); et $id = $product->id; si pas de variant.

$id = $variant ? sha1($product->id . $variant->name . $variant->price) : $product->id;
Muxxable, il y a 7 ans

J'avais pas vu cette solution là ! Merci pour le coup de main, ça fonctionne plutôt bien

rueduphp, il y a 7 ans

Au plaisir :)