diff --git a/README.md b/README.md index 3481422..06c7ffd 100644 --- a/README.md +++ b/README.md @@ -545,6 +545,14 @@ If you want to merge the cart with another one from the database, all you have t // Merge the contents of 'savedcart' into 'username'. Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); +### Erasing the cart +If you want to erase the cart from the database, all you have to do is call the `erase($identifier)` where `$identifier` is the key you specified for the `store` method. + + Cart::erase('username'); + + // To erase a cart switching to an instance named 'wishlist' + Cart::instance('wishlist')->erase('username'); + ## Exceptions The Cart package will throw exceptions if something goes wrong. This way it's easier to debug your code using the Cart package or to handle the error based on the type of exceptions. The Cart packages can throw the following exceptions: @@ -566,6 +574,7 @@ The cart also has events build in. There are five events available for you to li | cart.removed | When an item is removed from the cart. | The `CartItem` that was removed. | | cart.stored | When the content of a cart was stored. | - | | cart.restored | When the content of a cart was restored. | - | +| cart.erased | When the content of a cart was erased. | - | ## Example diff --git a/src/Cart.php b/src/Cart.php index 97097a0..4a0d28c 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -628,6 +628,29 @@ class Cart ->where('identifier', $identifier)->delete(); } + /** + * Erase the cart with the given identifier. + * + * @param mixed $identifier + * + * @return void + */ + public function erase($identifier) + { + if ($identifier instanceof InstanceIdentifier) { + $identifier = $identifier->getInstanceIdentifier(); + } + + if (!$this->storedCartWithIdentifierExists($identifier)) { + return; + } + + $this->getConnection()->table($this->getTableName()) + ->where('identifier', $identifier)->delete(); + + $this->events->dispatch('cart.erased'); + } + /** * Merges the contents of another cart into this cart. * diff --git a/tests/CartTest.php b/tests/CartTest.php index e9acea9..484e76b 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1189,6 +1189,28 @@ class CartTest extends TestCase $this->assertEquals('large', $cartItem->options->size); } + /** @test */ + public function it_can_erase_a_cart_from_the_database() + { + $this->artisan('migrate', [ + '--database' => 'testing', + ]); + + Event::fake(); + + $cart = $this->getCart(); + + $cart->add(new BuyableProduct()); + + $cart->store($identifier = 123); + + $cart->erase($identifier); + + $this->assertDatabaseMissing('shoppingcart', ['identifier' => $identifier, 'instance' => 'default']); + + Event::assertDispatched('cart.erased'); + } + /** * Get an instance of the cart. *