From 4d302fb4a20714e7f6b63cda2c1c67b29a231444 Mon Sep 17 00:00:00 2001 From: Pascal Kousbroek Date: Fri, 29 Mar 2019 15:39:17 +0100 Subject: [PATCH 01/52] Update Cart.php, fix CartItem::fromAttributes call The CartItem::fromAttributes call is missing the $weight parameter, and the CartItemOptions don't work any more because of this. --- src/Cart.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Cart.php b/src/Cart.php index cbb2699..51e2add 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -710,7 +710,7 @@ class Cart $cartItem = CartItem::fromArray($id); $cartItem->setQuantity($id['qty']); } else { - $cartItem = CartItem::fromAttributes($id, $name, $price, $options); + $cartItem = CartItem::fromAttributes($id, $name, $price, null, $options); $cartItem->setQuantity($qty); } From 279e820760e8ccaf1a3b1a7ffe6f48b7083d243d Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Tue, 16 Apr 2019 12:10:06 +0200 Subject: [PATCH 02/52] Fixed weight integration, added testcase, fixed weird readme code example --- README.md | 6 +++--- src/Cart.php | 10 ++++++---- tests/CartTest.php | 13 +++++++++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c227e1c..b0340e3 100644 --- a/README.md +++ b/README.md @@ -41,16 +41,16 @@ The shoppingcart gives you the following methods to use: Adding an item to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters. -In its most basic form you can specify the id, name, quantity, price of the product you'd like to add to the cart. +In its most basic form you can specify the id, name, quantity, price and weight of the product you'd like to add to the cart. ```php -Cart::add('293ad', 'Product 1', 1, 9.99); +Cart::add('293ad', 'Product 1', 1, 9.99, 550); ``` As an optional fifth parameter you can pass it options, so you can add multiple items with the same id, but with (for instance) a different size. ```php -Cart::add('293ad', 'Product 1', 1, 9.99, 'weight' => 550, ['size' => 'large']); +Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); ``` **The `add()` method will return an CartItem instance of the item you just added to the cart.** diff --git a/src/Cart.php b/src/Cart.php index 51e2add..0e2269c 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -105,11 +105,12 @@ class Cart * @param mixed $name * @param int|float $qty * @param float $price + * @param float $weight * @param array $options * * @return \Gloudemans\Shoppingcart\CartItem */ - public function add($id, $name = null, $qty = null, $price = null, array $options = []) + public function add($id, $name = null, $qty = null, $price = null, $weight = null, array $options = []) { if ($this->isMulti($id)) { return array_map(function ($item) { @@ -117,7 +118,7 @@ class Cart }, $id); } - $cartItem = $this->createCartItem($id, $name, $qty, $price, $options); + $cartItem = $this->createCartItem($id, $name, $qty, $price, $weight, $options); return $this->addCartItem($cartItem); } @@ -696,11 +697,12 @@ class Cart * @param mixed $name * @param int|float $qty * @param float $price + * @param float $weight * @param array $options * * @return \Gloudemans\Shoppingcart\CartItem */ - private function createCartItem($id, $name, $qty, $price, array $options) + private function createCartItem($id, $name, $qty, $price, $weight, array $options) { if ($id instanceof Buyable) { $cartItem = CartItem::fromBuyable($id, $qty ?: []); @@ -710,7 +712,7 @@ class Cart $cartItem = CartItem::fromArray($id); $cartItem->setQuantity($id['qty']); } else { - $cartItem = CartItem::fromAttributes($id, $name, $price, null, $options); + $cartItem = CartItem::fromAttributes($id, $name, $price, $weight, $options); $cartItem->setQuantity($qty); } diff --git a/tests/CartTest.php b/tests/CartTest.php index b51863d..8fb366d 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1149,6 +1149,19 @@ class CartTest extends TestCase $this->assertEquals(2.50, $cart->tax(2)); // tax of 5 Bucks } + /** @test */ + public function it_does_allow_adding_cart_items_with_weight_and_options() + { + // https://github.com/bumbummen99/LaravelShoppingcart/pull/5 + $cart = $this->getCart(); + + $cartItem = $cart->add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); + + $this->assertEquals(550, $cartItem->weight); + $this->assertTrue($cartItem->options->has('size')); + $this->assertEquals('large', $cartItem->options->size); + } + /** * Get an instance of the cart. * From f4673140f791efa883eb8802058ca944faf03949 Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Tue, 16 Apr 2019 12:12:11 +0200 Subject: [PATCH 03/52] Codestyle --- tests/CartTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/CartTest.php b/tests/CartTest.php index 8fb366d..8c278e5 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1155,7 +1155,7 @@ class CartTest extends TestCase // https://github.com/bumbummen99/LaravelShoppingcart/pull/5 $cart = $this->getCart(); - $cartItem = $cart->add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); + $cartItem = $cart->add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); $this->assertEquals(550, $cartItem->weight); $this->assertTrue($cartItem->options->has('size')); From 9e35faece2dcc1497528cc0d7ae7b908a8d9e521 Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Sun, 12 May 2019 17:23:14 +0200 Subject: [PATCH 04/52] Add validation and exception for weight to CartItem Constructor --- src/CartItem.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/CartItem.php b/src/CartItem.php index 0717ed7..e5ac8ac 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -97,6 +97,9 @@ class CartItem implements Arrayable, Jsonable if (strlen($price) < 0 || !is_numeric($price)) { throw new \InvalidArgumentException('Please supply a valid price.'); } + if (strlen($weight) < 0 || !is_numeric($weight)) { + throw new \InvalidArgumentException('Please supply a valid weight.'); + } $this->id = $id; $this->name = $name; From 8f186e5edfeca00d3ee6aa67756fb396f1402d37 Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Wed, 19 Jun 2019 18:02:26 +0200 Subject: [PATCH 05/52] Added homepages to authors --- composer.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index daac79e..23a9b02 100644 --- a/composer.json +++ b/composer.json @@ -6,11 +6,13 @@ "authors": [ { "name": "Rob Gloudemans", - "email": "info@robgloudemans.nl" + "email": "info@robgloudemans.nl", + "homepage": "http://robgloudemans.nl/" }, { "name": "Patrick Henninger", - "email": "privat@skyraptor.eu" + "email": "privat@skyraptor.eu", + "homepage": "https://skyraptor.eu/" } ], "require": { From 9d6a5dab8c34c20a890157cf61b75607d2fb3ec4 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sun, 23 Jun 2019 00:11:50 +0200 Subject: [PATCH 06/52] Update CartItem.php Remove strlen from weight --- src/CartItem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CartItem.php b/src/CartItem.php index e5ac8ac..8066d8d 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -97,7 +97,7 @@ class CartItem implements Arrayable, Jsonable if (strlen($price) < 0 || !is_numeric($price)) { throw new \InvalidArgumentException('Please supply a valid price.'); } - if (strlen($weight) < 0 || !is_numeric($weight)) { + if (!is_numeric($weight)) { throw new \InvalidArgumentException('Please supply a valid weight.'); } From 0c36a1d72e498eac2e5924a56200a764e93a2497 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sun, 23 Jun 2019 00:24:25 +0200 Subject: [PATCH 07/52] Update CartItem.php Revert last change --- src/CartItem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CartItem.php b/src/CartItem.php index 8066d8d..16b448b 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -97,7 +97,7 @@ class CartItem implements Arrayable, Jsonable if (strlen($price) < 0 || !is_numeric($price)) { throw new \InvalidArgumentException('Please supply a valid price.'); } - if (!is_numeric($weight)) { + if (strlen($price) < 0 || !is_numeric($weight)) { throw new \InvalidArgumentException('Please supply a valid weight.'); } From ecb4d9717a805b5af19c99733742d6ad78494d49 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sun, 23 Jun 2019 00:25:32 +0200 Subject: [PATCH 08/52] Update Cart.php Changed default value of $weight to 0 --- src/Cart.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Cart.php b/src/Cart.php index 0e2269c..97097a0 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -110,7 +110,7 @@ class Cart * * @return \Gloudemans\Shoppingcart\CartItem */ - public function add($id, $name = null, $qty = null, $price = null, $weight = null, array $options = []) + public function add($id, $name = null, $qty = null, $price = null, $weight = 0, array $options = []) { if ($this->isMulti($id)) { return array_map(function ($item) { From a464a240e8f0337f6f1f4a6e11a80ea4dbb118f2 Mon Sep 17 00:00:00 2001 From: Patrick Date: Wed, 26 Jun 2019 15:36:53 +0200 Subject: [PATCH 09/52] Update CartTest.php Added Test for CartItem.php invalid weight exception. --- tests/CartTest.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/CartTest.php b/tests/CartTest.php index 8c278e5..611ae37 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -263,6 +263,19 @@ class CartTest extends TestCase $cart->add(1, 'Some title', 1, 'invalid'); } + + /** + * @test + */ + public function it_will_validate_the_weight() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Please supply a valid weight'); + + $cart = $this->getCart(); + + $cart->add(1, 'Some title', 1, 10.00, 'invalid'); + } /** @test */ public function it_will_update_the_cart_if_the_item_already_exists_in_the_cart() From d78b555aa17a8bbdec3b3b12bcad4b1c83bcb512 Mon Sep 17 00:00:00 2001 From: Patrick Date: Wed, 26 Jun 2019 15:38:40 +0200 Subject: [PATCH 10/52] Update CartTest.php Codestyle --- tests/CartTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/CartTest.php b/tests/CartTest.php index 611ae37..fc8f6ab 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -263,7 +263,7 @@ class CartTest extends TestCase $cart->add(1, 'Some title', 1, 'invalid'); } - + /** * @test */ From 30cd02f5f883ffda4e1a74158b35347d138bddcd Mon Sep 17 00:00:00 2001 From: Patrick Date: Wed, 26 Jun 2019 15:48:14 +0200 Subject: [PATCH 11/52] Update README.md https://github.com/bumbummen99/LaravelShoppingcart/issues/11 Fixed copypasta in the Readme --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b0340e3..a8ceb0b 100644 --- a/README.md +++ b/README.md @@ -306,8 +306,8 @@ $cart->setTax($rowId, 21); You can use the `setGlobalTax()` method to change the tax rate for all items in the cart. New items will receive the setGlobalTax as well. ```php -Cart::setGlobalDiscount(21); -$cart->setGlobalDiscount(21); +Cart::setGlobalTax(21); +$cart->setGlobalTax(21); ``` ### Cart::setGlobalDiscount($discountRate) @@ -315,8 +315,8 @@ $cart->setGlobalDiscount(21); You can use the `setGlobalDiscount()` method to change the discount rate for all items in the cart. New items will receive the discount as well. ```php -Cart::setGlobalDiscount(21); -$cart->setGlobalDiscount(21); +Cart::setGlobalDiscount(50); +$cart->setGlobalDiscount(50); ``` ### Cart::setDiscount($rowId, $taxRate) From 74607eb5ebd513d5a87ab9fe0dd25987e05a6a1c Mon Sep 17 00:00:00 2001 From: Patrick Date: Wed, 26 Jun 2019 15:53:08 +0200 Subject: [PATCH 12/52] Update ShoppingcartServiceProvider.php https://github.com/bumbummen99/LaravelShoppingcart/issues/8 Added missing publish group parameter --- src/ShoppingcartServiceProvider.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ShoppingcartServiceProvider.php b/src/ShoppingcartServiceProvider.php index a26ef89..2e6b1b5 100644 --- a/src/ShoppingcartServiceProvider.php +++ b/src/ShoppingcartServiceProvider.php @@ -30,6 +30,6 @@ class ShoppingcartServiceProvider extends ServiceProvider $this->publishes([ realpath(__DIR__.'/Database/migrations') => $this->app->databasePath().'/migrations', - ]); + ], 'migrations'); } } From a79ed9ff6ef2ddb79f4ae4bd1b0e1608c7f52836 Mon Sep 17 00:00:00 2001 From: Salim Djerbouh Date: Sun, 30 Jun 2019 15:05:04 +0100 Subject: [PATCH 13/52] fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8ceb0b..b77ead2 100644 --- a/README.md +++ b/README.md @@ -339,7 +339,7 @@ use Gloudemans\Shoppingcart\Contracts\Buyable; use Illuminate\Database\Eloquent\Model; class Product extends Model implements Buyable { - use Gloudemans\Shoppingcart\CanBeNought; + use Gloudemans\Shoppingcart\CanBeBought; } ``` From bcc43079e36679e81fc7e766efdd017ca2f31955 Mon Sep 17 00:00:00 2001 From: Dan Tomlinson Date: Fri, 6 Sep 2019 16:47:53 +0100 Subject: [PATCH 14/52] Updated composer.json to allow Laravel 6.0 dependencies --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 23a9b02..afe96ff 100644 --- a/composer.json +++ b/composer.json @@ -16,9 +16,9 @@ } ], "require": { - "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*", - "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*", - "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*" + "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*", + "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*", + "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*" }, "require-dev": { "phpunit/phpunit": "~5.0||~6.0||~7.0||~8.0", From 7401f5bbb171caa91ba3a20443085f6f2d85f214 Mon Sep 17 00:00:00 2001 From: Dan Tomlinson Date: Fri, 6 Sep 2019 16:49:42 +0100 Subject: [PATCH 15/52] Replaced array_get with Arr::get as the helper method has been removed in 6.0 --- src/CartItem.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/CartItem.php b/src/CartItem.php index 16b448b..579c6b6 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -5,6 +5,7 @@ namespace Gloudemans\Shoppingcart; use Gloudemans\Shoppingcart\Contracts\Buyable; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; +use Illuminate\Support\Arr; class CartItem implements Arrayable, Jsonable { @@ -289,13 +290,13 @@ class CartItem implements Arrayable, Jsonable */ public function updateFromArray(array $attributes) { - $this->id = array_get($attributes, 'id', $this->id); - $this->qty = array_get($attributes, 'qty', $this->qty); - $this->name = array_get($attributes, 'name', $this->name); - $this->price = array_get($attributes, 'price', $this->price); - $this->weight = array_get($attributes, 'weight', $this->weight); + $this->id = Arr::get($attributes, 'id', $this->id); + $this->qty = Arr::get($attributes, 'qty', $this->qty); + $this->name = Arr::get($attributes, 'name', $this->name); + $this->price = Arr::get($attributes, 'price', $this->price); + $this->weight = Arr::get($attributes, 'weight', $this->weight); $this->priceTax = $this->price + $this->tax; - $this->options = new CartItemOptions(array_get($attributes, 'options', $this->options)); + $this->options = new CartItemOptions(Arr::get($attributes, 'options', $this->options)); $this->rowId = $this->generateRowId($this->id, $this->options->all()); } @@ -412,7 +413,7 @@ class CartItem implements Arrayable, Jsonable */ public static function fromArray(array $attributes) { - $options = array_get($attributes, 'options', []); + $options = Arr::get($attributes, 'options', []); return new self($attributes['id'], $attributes['name'], $attributes['price'], $attributes['weight'], $options); } From 6f9aace218d5841817026f98290d672b2ac0b83d Mon Sep 17 00:00:00 2001 From: Patrick Date: Fri, 6 Sep 2019 18:00:29 +0200 Subject: [PATCH 16/52] Updated Laravel version in the readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b77ead2..3481422 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 5.8. +This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. ## Installation From 14e8a405347752b2cfde1689d5fce30dacac357a Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Fri, 27 Sep 2019 19:00:10 +0200 Subject: [PATCH 17/52] Changed $taxRate from private to public, Solve https://github.com/Crinsane/LaravelShoppingcart/issues/436 --- src/CartItem.php | 14 +++++++------- tests/CartTest.php | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/CartItem.php b/src/CartItem.php index 579c6b6..5a49ef2 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -58,6 +58,13 @@ class CartItem implements Arrayable, Jsonable */ public $options; + /** + * The tax rate for the cart item. + * + * @var int|float + */ + public $taxRate = 0; + /** * The FQN of the associated model. * @@ -65,13 +72,6 @@ class CartItem implements Arrayable, Jsonable */ private $associatedModel = null; - /** - * The tax rate for the cart item. - * - * @var int|float - */ - private $taxRate = 0; - /** * The discount rate for the cart item. * diff --git a/tests/CartTest.php b/tests/CartTest.php index fc8f6ab..e9acea9 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -756,6 +756,20 @@ class CartTest extends TestCase $this->assertEquals('1.050,00', $cart->tax(2, ',', '.')); } + /** @test */ + public function it_can_access_tax_as_percentage() + { + $cart = $this->getCart(); + + $cart->add(new BuyableProduct(1, 'Some title', 10.00), 1); + + $cart->setTax('027c91341fd5cf4d2579b49c4b6a90da', 19); + + $cartItem = $cart->get('027c91341fd5cf4d2579b49c4b6a90da'); + + $this->assertEquals(19, $cartItem->taxRate); + } + /** @test */ public function it_can_return_the_subtotal() { From 015b2a8607b90d0eeff79970fd0b958eff097682 Mon Sep 17 00:00:00 2001 From: Patrick Date: Fri, 4 Oct 2019 09:54:04 +0200 Subject: [PATCH 18/52] Update composer.json Should also support Laravel 6.1 --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index afe96ff..e871ef2 100644 --- a/composer.json +++ b/composer.json @@ -16,9 +16,9 @@ } ], "require": { - "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*", - "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*", - "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||6.0.*" + "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0", + "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0", + "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0" }, "require-dev": { "phpunit/phpunit": "~5.0||~6.0||~7.0||~8.0", From 950e3de7d8e05cde8c2a1776a6547ba87d5d1a7d Mon Sep 17 00:00:00 2001 From: LucyIkonnikova-Skutsenia Date: Fri, 18 Oct 2019 00:11:01 +0300 Subject: [PATCH 19/52] Add README_uk-UA.md --- README_uk-UA.md | 627 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 627 insertions(+) create mode 100644 README_uk-UA.md diff --git a/README_uk-UA.md b/README_uk-UA.md new file mode 100644 index 0000000..3481422 --- /dev/null +++ b/README_uk-UA.md @@ -0,0 +1,627 @@ +## LaravelShoppingcart +[![Build Status](https://travis-ci.org/bumbummen99/LaravelShoppingcart.png?branch=master)](https://travis-ci.org/bumbummen99/LaravelShoppingcart) +[![codecov](https://codecov.io/gh/bumbummen99/LaravelShoppingcart/branch/master/graph/badge.svg)](https://codecov.io/gh/bumbummen99/LaravelShoppingcart) +[![StyleCI](https://styleci.io/repos/152610878/shield?branch=master)](https://styleci.io/repos/152610878) +[![Total Downloads](https://poser.pugx.org/bumbummen99/shoppingcart/downloads.png)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![Latest Stable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/stable)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) + +This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. + +## Installation + +Install the [package](https://packagist.org/packages/bumbummen99/shoppingcart) through [Composer](http://getcomposer.org/). + +Run the Composer require command from the Terminal: + + composer require bumbummen99/shoppingcart + +Now you're ready to start using the shoppingcart in your application. + +**As of version 2 of this package it's possibly to use dependency injection to inject an instance of the Cart class into your controller or other class** + +## Overview +Look at one of the following topics to learn more about LaravelShoppingcart + +* [Usage](#usage) +* [Collections](#collections) +* [Instances](#instances) +* [Models](#models) +* [Database](#database) +* [Exceptions](#exceptions) +* [Events](#events) +* [Example](#example) + +## Usage + +The shoppingcart gives you the following methods to use: + +### Cart::add() + +Adding an item to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters. + +In its most basic form you can specify the id, name, quantity, price and weight of the product you'd like to add to the cart. + +```php +Cart::add('293ad', 'Product 1', 1, 9.99, 550); +``` + +As an optional fifth parameter you can pass it options, so you can add multiple items with the same id, but with (for instance) a different size. + +```php +Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); +``` + +**The `add()` method will return an CartItem instance of the item you just added to the cart.** + +Maybe you prefer to add the item using an array? As long as the array contains the required keys, you can pass it to the method. The options key is optional. + +```php +Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); +``` + +New in version 2 of the package is the possibility to work with the [Buyable](#buyable) interface. The way this works is that you have a model implement the [Buyable](#buyable) interface, which will make you implement a few methods so the package knows how to get the id, name and price from your model. +This way you can just pass the `add()` method a model and the quantity and it will automatically add it to the cart. + +**As an added bonus it will automatically associate the model with the CartItem** + +```php +Cart::add($product, 1, ['size' => 'large']); +``` +As an optional third parameter you can add options. +```php +Cart::add($product, 1, ['size' => 'large']); +``` + +Finally, you can also add multipe items to the cart at once. +You can just pass the `add()` method an array of arrays, or an array of Buyables and they will be added to the cart. + +**When adding multiple items to the cart, the `add()` method will return an array of CartItems.** + +```php +Cart::add([ + ['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00, 'weight' => 550], + ['id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'weight' => 550, 'options' => ['size' => 'large']] +]); + +Cart::add([$product1, $product2]); + +``` + +### Cart::update() + +To update an item in the cart, you'll first need the rowId of the item. +Next you can use the `update()` method to update it. + +If you simply want to update the quantity, you'll pass the update method the rowId and the new quantity: + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::update($rowId, 2); // Will update the quantity +``` + +If you want to update more attributes of the item, you can either pass the update method an array or a `Buyable` as the second parameter. This way you can update all information of the item with the given rowId. + +```php +Cart::update($rowId, ['name' => 'Product 1']); // Will update the name + +Cart::update($rowId, $product); // Will update the id, name and price + +``` + +### Cart::remove() + +To remove an item for the cart, you'll again need the rowId. This rowId you simply pass to the `remove()` method and it will remove the item from the cart. + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::remove($rowId); +``` + +### Cart::get() + +If you want to get an item from the cart using its rowId, you can simply call the `get()` method on the cart and pass it the rowId. + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::get($rowId); +``` + +### Cart::content() + +Of course you also want to get the carts content. This is where you'll use the `content` method. This method will return a Collection of CartItems which you can iterate over and show the content to your customers. + +```php +Cart::content(); +``` + +This method will return the content of the current cart instance, if you want the content of another instance, simply chain the calls. + +```php +Cart::instance('wishlist')->content(); +``` + +### Cart::destroy() + +If you want to completely remove the content of a cart, you can call the destroy method on the cart. This will remove all CartItems from the cart for the current cart instance. + +```php +Cart::destroy(); +``` + +### Cart::weight() + +The `weight()` method can be used to get the weight total of all items in the cart, given there weight and quantity. + +```php +Cart::weight(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::weight($decimals, $decimalSeperator, $thousandSeperator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->weight`** + +### Cart::total() + +The `total()` method can be used to get the calculated total of all items in the cart, given there price and quantity. + +```php +Cart::total(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::total($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->total`** + +### Cart::tax() + +The `tax()` method can be used to get the calculated amount of tax for all items in the cart, given there price and quantity. + +```php +Cart::tax(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::tax($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the tax property `$cart->tax`** + +### Cart::subtotal() + +The `subtotal()` method can be used to get the total of all items in the cart, minus the total amount of tax. + +```php +Cart::subtotal(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::subtotal($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->subtotal`** + +### Cart::discount() + +The `discount()` method can be used to get the total discount of all items in the cart. + +```php +Cart::discount(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::discount($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->discount`** + +### Cart::initial() + +The `initial()` method can be used to get the total price of all items in the cart before discount. + +```php +Cart::initial(); +``` + +The method will automatically format the result, which you can tweak using the three optional parameters + +```php +Cart::initial($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->initial`** + +### Cart::count() + +If you want to know how many items there are in your cart, you can use the `count()` method. This method will return the total number of items in the cart. So if you've added 2 books and 1 shirt, it will return 3 items. + +```php +Cart::count(); +$cart->count(); +``` + +### Cart::search() + +To find an item in the cart, you can use the `search()` method. + +**This method was changed on version 2** + +Behind the scenes, the method simply uses the filter method of the Laravel Collection class. This means you must pass it a Closure in which you'll specify you search terms. + +If you for instance want to find all items with an id of 1: + +```php +$cart->search(function ($cartItem, $rowId) { + return $cartItem->id === 1; +}); +``` + +As you can see the Closure will receive two parameters. The first is the CartItem to perform the check against. The second parameter is the rowId of this CartItem. + +**The method will return a Collection containing all CartItems that where found** + +This way of searching gives you total control over the search process and gives you the ability to create very precise and specific searches. + +### Cart::setTax($rowId, $taxRate) + +You can use the `setTax()` method to change the tax rate that applies to the CartItem. This will overwrite the value set in the config file. + +```php +Cart::setTax($rowId, 21); +$cart->setTax($rowId, 21); +``` + +### Cart::setGlobalTax($taxRate) + +You can use the `setGlobalTax()` method to change the tax rate for all items in the cart. New items will receive the setGlobalTax as well. + +```php +Cart::setGlobalTax(21); +$cart->setGlobalTax(21); +``` + +### Cart::setGlobalDiscount($discountRate) + +You can use the `setGlobalDiscount()` method to change the discount rate for all items in the cart. New items will receive the discount as well. + +```php +Cart::setGlobalDiscount(50); +$cart->setGlobalDiscount(50); +``` + +### Cart::setDiscount($rowId, $taxRate) + +You can use the `setDiscount()` method to change the discount rate that applies a CartItem. Keep in mind that this value will be changed if you set the global discount for the Cart afterwards. + +```php +Cart::setDiscount($rowId, 21); +$cart->setDiscount($rowId, 21); +``` + +### Buyable + +For the convenience of faster adding items to cart and their automatic association, your model has to implement the `Buyable` interface. You can use the `CanBeBought` trait to implement the required methods but keep in mind that these will use predefined fields on your model for the required values. +```php +id; + } + public function getBuyableDescription(){ + return $this->name; + } + public function getBuyablePrice(){ + return $this->price; + } + public function getBuyableWeight(){ + return $this->weight; + } +``` + +Example: + +```php +id; + } + public function getBuyableDescription($options = null) { + return $this->name; + } + public function getBuyablePrice($options = null) { + return $this->price; + } +} +``` + +## Collections + +On multiple instances the Cart will return to you a Collection. This is just a simple Laravel Collection, so all methods you can call on a Laravel Collection are also available on the result. + +As an example, you can quicky get the number of unique products in a cart: + +```php +Cart::content()->count(); +``` + +Or you can group the content by the id of the products: + +```php +Cart::content()->groupBy('id'); +``` + +## Instances + +The packages supports multiple instances of the cart. The way this works is like this: + +You can set the current instance of the cart by calling `Cart::instance('newInstance')`. From this moment, the active instance of the cart will be `newInstance`, so when you add, remove or get the content of the cart, you're work with the `newInstance` instance of the cart. +If you want to switch instances, you just call `Cart::instance('otherInstance')` again, and you're working with the `otherInstance` again. + +So a little example: + +```php +Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); + +// Get the content of the 'shopping' cart +Cart::content(); + +Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, 550, ['size' => 'medium']); + +// Get the content of the 'wishlist' cart +Cart::content(); + +// If you want to get the content of the 'shopping' cart again +Cart::instance('shopping')->content(); + +// And the count of the 'wishlist' cart again +Cart::instance('wishlist')->count(); +``` + +You can also use the `InstanceIdentifier` Contract to extend a desired Model to assign / create a Cart instance for it. This also allows to directly set the global discount. +``` +email; + } + + /** + * Get the unique identifier to load the Cart from + * + * @return int|string + */ + public function getInstanceGlobalDiscount($options = null) + { + return $this->discountRate ?: 0; + } +} + +// Inside Controller +$user = \Auth::user(); +$cart = Cart::instance($user); + + + +``` + +**N.B. Keep in mind that the cart stays in the last set instance for as long as you don't set a different one during script execution.** + +**N.B.2 The default cart instance is called `default`, so when you're not using instances,`Cart::content();` is the same as `Cart::instance('default')->content()`.** + +## Models + +Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. Let's say you have a `Product` model in your application. With the `associate()` method, you can tell the cart that an item in the cart, is associated to the `Product` model. + +That way you can access your model right from the `CartItem`! + +The model can be accessed via the `model` property on the CartItem. + +**If your model implements the `Buyable` interface and you used your model to add the item to the cart, it will associate automatically.** + +Here is an example: + +```php + +// First we'll add the item to the cart. +$cartItem = Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); + +// Next we associate a model with the item. +Cart::associate($cartItem->rowId, 'Product'); + +// Or even easier, call the associate method on the CartItem! +$cartItem->associate('Product'); + +// You can even make it a one-liner +Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large'])->associate('Product'); + +// Now, when iterating over the content of the cart, you can access the model. +foreach(Cart::content() as $row) { + echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.'; +} +``` +## Database + +- [Config](#configuration) +- [Storing the cart](#storing-the-cart) +- [Restoring the cart](#restoring-the-cart) + +### Configuration +To save cart into the database so you can retrieve it later, the package needs to know which database connection to use and what the name of the table is. +By default the package will use the default database connection and use a table named `shoppingcart`. +If you want to change these options, you'll have to publish the `config` file. + + php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config" + +This will give you a `cart.php` config file in which you can make the changes. + +To make your life easy, the package also includes a ready to use `migration` which you can publish by running: + + php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations" + +This will place a `shoppingcart` table's migration file into `database/migrations` directory. Now all you have to do is run `php artisan migrate` to migrate your database. + +### Storing the cart +To store your cart instance into the database, you have to call the `store($identifier) ` method. Where `$identifier` is a random key, for instance the id or username of the user. + + Cart::store('username'); + + // To store a cart instance named 'wishlist' + Cart::instance('wishlist')->store('username'); + +### Restoring the cart +If you want to retrieve the cart from the database and restore it, all you have to do is call the `restore($identifier)` where `$identifier` is the key you specified for the `store` method. + + Cart::restore('username'); + + // To restore a cart instance named 'wishlist' + Cart::instance('wishlist')->restore('username'); + +### Merge the cart +If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items. + + // Merge the contents of 'savedcart' into 'username'. + Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); + +## 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: + +| Exception | Reason | +| ---------------------------- | ---------------------------------------------------------------------------------- | +| *CartAlreadyStoredException* | When trying to store a cart that was already stored using the specified identifier | +| *InvalidRowIDException* | When the rowId that got passed doesn't exists in the current cart instance | +| *UnknownModelException* | When you try to associate an none existing model to a CartItem. | + +## Events + +The cart also has events build in. There are five events available for you to listen for. + +| Event | Fired | Parameter | +| ------------- | ---------------------------------------- | -------------------------------- | +| cart.added | When an item was added to the cart. | The `CartItem` that was added. | +| cart.updated | When an item in the cart was updated. | The `CartItem` that was updated. | +| 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. | - | + +## Example + +Below is a little example of how to list the cart content in a table: + +```php + +// Add some items in your Controller. +Cart::add('192ao12', 'Product 1', 1, 9.99); +Cart::add('1239ad0', 'Product 2', 2, 5.95, ['size' => 'large']); + +// Display the content in a View. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ProductQtyPriceSubtotal
+

name; ?>

+

options->has('size') ? $row->options->size : ''); ?>

+
$price; ?>$total; ?>
 Subtotal
 Tax
 Total
+``` From 77e7acd50aa28f30405b0057f139ff1299e5b4bf Mon Sep 17 00:00:00 2001 From: LucyIkonnikova-Skutsenia Date: Fri, 18 Oct 2019 13:09:20 +0300 Subject: [PATCH 20/52] Add Ukrainian translation of README.md - needs proofreading --- README_uk-UA.md | 257 ++++++++++++++++++++++++------------------------ 1 file changed, 128 insertions(+), 129 deletions(-) diff --git a/README_uk-UA.md b/README_uk-UA.md index 3481422..9ea183a 100644 --- a/README_uk-UA.md +++ b/README_uk-UA.md @@ -7,77 +7,76 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. +Цей репозиторій є відгалуженням [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) з додатковими незначними фічамиб сумісними з Laravel 6. -## Installation +## Встановлення -Install the [package](https://packagist.org/packages/bumbummen99/shoppingcart) through [Composer](http://getcomposer.org/). +Встановіть [пакет](https://packagist.org/packages/bumbummen99/shoppingcart) скориставшись [Завантажувачем](http://getcomposer.org/). -Run the Composer require command from the Terminal: +Для запуску Завантажувача, скористайтеся командою у Терміналі: composer require bumbummen99/shoppingcart -Now you're ready to start using the shoppingcart in your application. +Тепер ви готові розпочати користуватися кошиком у вашому застосунку. -**As of version 2 of this package it's possibly to use dependency injection to inject an instance of the Cart class into your controller or other class** +**Починаючи з версії 2 даного пакету з'явилася можливість впровадження залежності для впровадження екземплера класу Кошик (Cart) до вашого контролера або іншого класу** -## Overview -Look at one of the following topics to learn more about LaravelShoppingcart +## Огляд +Щоб детальніше ознайомитися LaravelShoppingcart, можете пройти за посиланнями -* [Usage](#usage) -* [Collections](#collections) -* [Instances](#instances) -* [Models](#models) -* [Database](#database) -* [Exceptions](#exceptions) -* [Events](#events) -* [Example](#example) +* [Застосування](#usage) +* [Колекції](#collections) +* [Екземпляри](#instances) +* [Моделі](#models) +* [База даних](#database) +* [Винятки](#exceptions) +* [Події](#events) +* [Приклад](#example) -## Usage +## Застосування -The shoppingcart gives you the following methods to use: +Кошик (Cart) дозволяє вам скористатися наступними методами: ### Cart::add() -Adding an item to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters. +Додавати покупки у кошик дуже зручно - достатньо лише скористатися методом `add()`, який приймає різноманітні параметри. -In its most basic form you can specify the id, name, quantity, price and weight of the product you'd like to add to the cart. +У найпростішій формі метода достатньо вказати ідентифікатор, назву, кількість, ціну та вагу товару, який ви хочете додати у кошик. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550); ``` -As an optional fifth parameter you can pass it options, so you can add multiple items with the same id, but with (for instance) a different size. +У якості додаткового п'ятого параметра можна задати варіанти, наприклад, щоб додати декілька одиниць з однаковим ідентифікатором, але різного розміру. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); ``` -**The `add()` method will return an CartItem instance of the item you just added to the cart.** +**Метод `add()` повертає екземпляр CartItems того товару, який ви щойно додали у кошик.** -Maybe you prefer to add the item using an array? As long as the array contains the required keys, you can pass it to the method. The options key is optional. +Можливо, вам більше до вподоби додавати товари, використовуючи масив? Якщо масив містить усі необхідні поля, ви можете передавати масив у цей метод. Поле із додатковими варіантами є необов'язковим. ```php Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); ``` -New in version 2 of the package is the possibility to work with the [Buyable](#buyable) interface. The way this works is that you have a model implement the [Buyable](#buyable) interface, which will make you implement a few methods so the package knows how to get the id, name and price from your model. -This way you can just pass the `add()` method a model and the quantity and it will automatically add it to the cart. +У версії 2 пакета з'явилася нова можливість для роботи з інтерфейсом [Buyable](#buyable). Такий функціонал з'являється за рахунок того, що модель запускає інтерфейс [Buyable](#buyable), який дозволить імплементувати декілька методів, з яких пакет знатиме як отримати ідентифікатор, назву та ціну з вашої моделі. +Таким чином, ви можете передати метод `add()` та кількість одиниць товару до моделі, а вона автоматично додасть їх до кошика. -**As an added bonus it will automatically associate the model with the CartItem** +**Додатковий бонус інтерфейсу - автоматичне об'єднання моделі з CartItems** ```php Cart::add($product, 1, ['size' => 'large']); ``` -As an optional third parameter you can add options. +У якості додаткового параметра, ви можете додати варіанти. ```php Cart::add($product, 1, ['size' => 'large']); ``` -Finally, you can also add multipe items to the cart at once. -You can just pass the `add()` method an array of arrays, or an array of Buyables and they will be added to the cart. +Нарешті, ви також можете додавати до кошика декілька одиниць водночас. Для цього потрібно передати у `add()` масив масивів або масив Покупні, і їх буде додано в кошик. -**When adding multiple items to the cart, the `add()` method will return an array of CartItems.** +**Під час додавання декількох одиниць товару в кошик, метод `add()` повертає масив CartItems.** ```php Cart::add([ @@ -91,10 +90,10 @@ Cart::add([$product1, $product2]); ### Cart::update() -To update an item in the cart, you'll first need the rowId of the item. -Next you can use the `update()` method to update it. +Щоб оновити товар у кошику, вам знадобиться ідентифікатор рядка (rowId) даного товару. +Далі ви можете скористатися методом `update()` для того, щоб оновити його. -If you simply want to update the quantity, you'll pass the update method the rowId and the new quantity: +Якщо ви просто хочете оновити кількість товару, вам потрібно передати у метод `update()` rowId і оновлену кількість: ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -102,7 +101,7 @@ $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::update($rowId, 2); // Will update the quantity ``` -If you want to update more attributes of the item, you can either pass the update method an array or a `Buyable` as the second parameter. This way you can update all information of the item with the given rowId. +Якщо ви хочете оновити більше атрибутів товару, вам потрібно або передати у метод `update()` масив або `Buyable` у якості другого параметра. Таким чином, ви можете оновити всю інформацію про товар за заданим rowId. ```php Cart::update($rowId, ['name' => 'Product 1']); // Will update the name @@ -113,7 +112,7 @@ Cart::update($rowId, $product); // Will update the id, name and price ### Cart::remove() -To remove an item for the cart, you'll again need the rowId. This rowId you simply pass to the `remove()` method and it will remove the item from the cart. +Щоб вилучити товар з кошика, вам знову знадобиться rowId. Такий rowId потрібно передати у метод `remove()`, який автоматично вилучить товар із кошика. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -123,7 +122,7 @@ Cart::remove($rowId); ### Cart::get() -If you want to get an item from the cart using its rowId, you can simply call the `get()` method on the cart and pass it the rowId. +Якщо ви хочете отримати товар із кошика, використовуючи його rowId, вам потрібно застосувати метод `get()` щодо кошика і передати в нього rowId. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -133,13 +132,13 @@ Cart::get($rowId); ### Cart::content() -Of course you also want to get the carts content. This is where you'll use the `content` method. This method will return a Collection of CartItems which you can iterate over and show the content to your customers. +Звісно, вам також може знадобитися отримати інформацію про вміст кошика. Для цього вам потрібно скористатися методом `content`. Такий метод повертає колекцію CartItems, ви можете перебирати вміст такої колекції і відобразити вміст кошика для ваших клієнтів. ```php Cart::content(); ``` -This method will return the content of the current cart instance, if you want the content of another instance, simply chain the calls. +Даний метод повертає вміст поточного екземпляра кошика, якщо ви хочете вміст іншого екземпляра, вам потрібно зв'язати виклики. ```php Cart::instance('wishlist')->content(); @@ -147,7 +146,7 @@ Cart::instance('wishlist')->content(); ### Cart::destroy() -If you want to completely remove the content of a cart, you can call the destroy method on the cart. This will remove all CartItems from the cart for the current cart instance. +Якщо ви хочете остаточно вилучити вміст кошика, ви можете застосувати метод `destroy()` щодо кошика. Даний метод вилучить всі CartItems з кошика для поточного екземпляра кошика. ```php Cart::destroy(); @@ -155,115 +154,115 @@ Cart::destroy(); ### Cart::weight() -The `weight()` method can be used to get the weight total of all items in the cart, given there weight and quantity. +Метод `weight()` можна застосувати, щоб отримати розрахунок ваги усіх товарів у кошику, за умови, що задано вагу і кількість одиниць. ```php Cart::weight(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::weight($decimals, $decimalSeperator, $thousandSeperator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->weight`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про вагу товарів через `$cart->weight`** ### Cart::total() -The `total()` method can be used to get the calculated total of all items in the cart, given there price and quantity. +Метод `total()` можна застосовувати, щоб отримати розрахунок вартості усіх товарів у кошику, за умови, що задані ціна і кількість одиниць. ```php Cart::total(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::total($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->total`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про вартість товарів через `$cart->total`** ### Cart::tax() -The `tax()` method can be used to get the calculated amount of tax for all items in the cart, given there price and quantity. +Метод `tax()` можна застосовувати, щоб отримати розрахунок суми податків для усіх товарів у кошику, за умови, що задані ціна і кількість одиниць. ```php Cart::tax(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::tax($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the tax property `$cart->tax`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про суму податку на товари через `$cart->tax`** ### Cart::subtotal() -The `subtotal()` method can be used to get the total of all items in the cart, minus the total amount of tax. +Метод `subtotal()` можна застосовувати, щоб отримати розрахунок вартості усіх товарів у кошику, без урахування суми податку. ```php Cart::subtotal(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::subtotal($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->subtotal`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про вартість усіх товарів без урахування суми податків через `$cart->subtotal`** ### Cart::discount() -The `discount()` method can be used to get the total discount of all items in the cart. +Метод `discount()` можна застосовувати, щоб отримати розрахунок знижки на усі товари у кошику. ```php Cart::discount(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::discount($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->discount`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про вартість усіх товарів з урахуванням знижки `$cart->discount`** ### Cart::initial() -The `initial()` method can be used to get the total price of all items in the cart before discount. +Метод `initial()` можна застосовувати, щоб отримати розрахунок вартості усіх товарів до застосування знижки. ```php Cart::initial(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Даний метод автоматично відформатує результат, який ви можете поправити за допомогою трьох додаткових параметрів. ```php Cart::initial($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Ви можете задати формат чисел за замовчуванням у файлі з конфігураціями. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->initial`** +**Якщо ви не використовуєте Фасад, але застосовуєте впровадження залежності, наприклад, у вашому Контролері, ви також можете отримати інформацію про вартість усіх товарів до застосування знижки `$cart->initial`** ### Cart::count() -If you want to know how many items there are in your cart, you can use the `count()` method. This method will return the total number of items in the cart. So if you've added 2 books and 1 shirt, it will return 3 items. +Метод `count()` можна застосовувати, щоб дізнатися кількість одиниць товарів у кошику. Даний метод повертає загальну кількість одиниць товарів у кошику. Тобто якщо ви додали 2 книжки і 1 сорочку, цей метод поверне 3 одиниці. ```php Cart::count(); @@ -272,13 +271,13 @@ $cart->count(); ### Cart::search() -To find an item in the cart, you can use the `search()` method. +Метод `search()` можна застосовувати, щоб знайти одиницю товару у кошику. -**This method was changed on version 2** +**Даний метод було змінено у версії 2** -Behind the scenes, the method simply uses the filter method of the Laravel Collection class. This means you must pass it a Closure in which you'll specify you search terms. +У своїй імплементації, цей метод застосовує метод фільтрування з класу Laravel Collection. Це означає, що вам потрібно передати замикання (Closure) для даного методу, де ви зазначите умови для пошуку. -If you for instance want to find all items with an id of 1: +Наприклад, якщо ви хочете знайти всі одиниці товару з ідентифікатором 1: ```php $cart->search(function ($cartItem, $rowId) { @@ -286,15 +285,15 @@ $cart->search(function ($cartItem, $rowId) { }); ``` -As you can see the Closure will receive two parameters. The first is the CartItem to perform the check against. The second parameter is the rowId of this CartItem. +Як ви можете побачити, замикання отримає 2 параметра. Перший - CartItem для здійснення перевірки щодо нього. Другий параметр - rowId даного CartItem. -**The method will return a Collection containing all CartItems that where found** +**Даний метод повертає колекцію, яка вміщує всі CartItems, які було знайдено** -This way of searching gives you total control over the search process and gives you the ability to create very precise and specific searches. +Такий спосіб пошуку надає вам повний контроль над процесом пошуку та дозволяє здійснювати дуже точні та конкретні пошуки. ### Cart::setTax($rowId, $taxRate) -You can use the `setTax()` method to change the tax rate that applies to the CartItem. This will overwrite the value set in the config file. +Метод `setTax()` можна застосовувати, щоб змінювати ставку оподаткування, яка застосовується до CartItem. Така операція перезапише значення встановлене у файлі з конфігураціями. ```php Cart::setTax($rowId, 21); @@ -303,7 +302,7 @@ $cart->setTax($rowId, 21); ### Cart::setGlobalTax($taxRate) -You can use the `setGlobalTax()` method to change the tax rate for all items in the cart. New items will receive the setGlobalTax as well. +Метод `setGlobalTax()` можна застосовувати, щоб змінити ставку оподаткування для усіх найменувать у кошику. Нові найменування отримають значення setGlobalTax також. ```php Cart::setGlobalTax(21); @@ -312,7 +311,7 @@ $cart->setGlobalTax(21); ### Cart::setGlobalDiscount($discountRate) -You can use the `setGlobalDiscount()` method to change the discount rate for all items in the cart. New items will receive the discount as well. +Метод `setGlobalDiscount()` можна застосовувати для заміни ставки знижки щодо усіх найменувань у кошику. Нові найменування також отримуватимуть таку знижку. ```php Cart::setGlobalDiscount(50); @@ -321,7 +320,7 @@ $cart->setGlobalDiscount(50); ### Cart::setDiscount($rowId, $taxRate) -You can use the `setDiscount()` method to change the discount rate that applies a CartItem. Keep in mind that this value will be changed if you set the global discount for the Cart afterwards. +Застосування методу `setDiscount()` полягає у заміні ставки знижки, яка застосовується до CartItem. Зверніть увагу, що дане значення ставки знижки буде змінено, якщо ви згодом встановите глобальну знижку для Кошика (Cart). ```php Cart::setDiscount($rowId, 21); @@ -330,7 +329,7 @@ $cart->setDiscount($rowId, 21); ### Buyable -For the convenience of faster adding items to cart and their automatic association, your model has to implement the `Buyable` interface. You can use the `CanBeBought` trait to implement the required methods but keep in mind that these will use predefined fields on your model for the required values. +Для зручності швидкого додавання товарів до кошика та їхнього автоматичної об'єднання, ваша модель повинна запустити інтерфейс `Buyable`. Ви можете застосовувати `CanBeBought` трейт для імплементації необхідних методів, але майте на увазі, що такі методи застосовуватимуть попередньо визначені поля у вашій моделі для необхідних значень. ```php count(); ``` -Or you can group the content by the id of the products: +Або групувати вміст за ідентифікатором товару: ```php Cart::content()->groupBy('id'); ``` -## Instances +## Екземпляри -The packages supports multiple instances of the cart. The way this works is like this: +Пакет підтримує декілька екземплярів кошика. Як це працює: -You can set the current instance of the cart by calling `Cart::instance('newInstance')`. From this moment, the active instance of the cart will be `newInstance`, so when you add, remove or get the content of the cart, you're work with the `newInstance` instance of the cart. -If you want to switch instances, you just call `Cart::instance('otherInstance')` again, and you're working with the `otherInstance` again. +Ви можете встановити поточний екземпляр кошика через виклик `Cart::instance('newInstance')`. З цього моменту, активний екземляр кошика буде `newInstance`, тому коли ви додаєте, вилучаєте або отримуєте інформацію щодо вмісту кошика, ви працюєте з екземпляром `newInstance` кошика. +Якщо ви хочете переключитися між екзмеплярами, ви можете викликати `Cart::instance('otherInstance')` ще раз, і ви знову працюватимете з `otherInstance`. -So a little example: +Невеликий приклад: ```php Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); @@ -425,7 +424,7 @@ Cart::instance('shopping')->content(); Cart::instance('wishlist')->count(); ``` -You can also use the `InstanceIdentifier` Contract to extend a desired Model to assign / create a Cart instance for it. This also allows to directly set the global discount. +Ви також можете використати Контракт `InstanceIdentifier` для розширення бажаної моделі можливістю призначення / створення екземпляру Кошика (Cart) для неї. Така дія також дозволить напряму встановлювати глобальну знижку. ``` content()`.** +**N.B.2 За замовчуванням екземпляр кошика називається `default`, тому коли ви не використовуєте екземпляри, `Cart::content();` залишається таким самим як і `Cart::instance('default')->content()`.** -## Models +## Моделі -Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. Let's say you have a `Product` model in your application. With the `associate()` method, you can tell the cart that an item in the cart, is associated to the `Product` model. +Через те, що це може бути дуже зручно мати можливість прямого доступу до моделі з CartItem, виникає питання чи можливо об'єднати модель із товарами у кошику. Скажімо, у вашому застосунку є модель `Product`. Завдяки методу `associate()` ви можете вказати кошику, що товар у кошику об'єднаний з моделлю `Product`. -That way you can access your model right from the `CartItem`! +Таким чином ви можете отримати доступ до вашої моделі одразу з `CartItem`! -The model can be accessed via the `model` property on the CartItem. +Доступ до моделі також можна отримати через властивість CartItem `model`. -**If your model implements the `Buyable` interface and you used your model to add the item to the cart, it will associate automatically.** +**Якщо ваша модель запускає інтерфейс `Buyable` і ви використовували вашу модель для додавання товару до кошика, вони будуть об'єднані автоматично.** -Here is an example: +Ось приклад: ```php @@ -502,74 +501,74 @@ foreach(Cart::content() as $row) { echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.'; } ``` -## Database +## База даних -- [Config](#configuration) -- [Storing the cart](#storing-the-cart) -- [Restoring the cart](#restoring-the-cart) +- [Конфігурації](#configuration) +- [Збереження кошика](#storing-the-cart) +- [Відновлення кошика](#restoring-the-cart) -### Configuration -To save cart into the database so you can retrieve it later, the package needs to know which database connection to use and what the name of the table is. -By default the package will use the default database connection and use a table named `shoppingcart`. -If you want to change these options, you'll have to publish the `config` file. +### Конфігурація +Для збереження кошика в базу даних, щоб ви могли отримати його пізніше, пакет повинен знати яке підключення до бази даних використовувати і яка назва окремої таблиці. +За замовчуванням, пакет використовуватиме підключення до бази даних, яке вказане за замовчуванням, та використовуватиме таблицію `shoppingcart`. +Якщо ви хочете змінити ці значення, вам потрібно буде опублікувати файл з конфігураціями `config`. php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config" -This will give you a `cart.php` config file in which you can make the changes. +Така дія надасть вам файл з конфігураціями `cart.php`, в якому ви можете внести бажані зміни. -To make your life easy, the package also includes a ready to use `migration` which you can publish by running: +Щоб спростити ваше життя, пакет також включає готову до вжитку `migration`, яку можна опублікувати через запуск настпої команди: php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations" -This will place a `shoppingcart` table's migration file into `database/migrations` directory. Now all you have to do is run `php artisan migrate` to migrate your database. +Така дія розмістить файл з міграцією таблиці `shoppingcart` в директорію `database/migrations`. Все що вам залишається зробити, це запустити `php artisan migrate` для міграції вашої бази даних. -### Storing the cart -To store your cart instance into the database, you have to call the `store($identifier) ` method. Where `$identifier` is a random key, for instance the id or username of the user. +### Збереження кошика +Для збереження екземпляра кошика до бази даних, вам потрібно викликати метод `store($identifier) `. Де `$identifier` є випадковим ключем, наприклад, ідентифікатор або ім'я користувача. Cart::store('username'); // To store a cart instance named 'wishlist' Cart::instance('wishlist')->store('username'); -### Restoring the cart -If you want to retrieve the cart from the database and restore it, all you have to do is call the `restore($identifier)` where `$identifier` is the key you specified for the `store` method. +### Відновлення кошика +Якщо ви хочете отримати кошик із бази даних і відновити його, вам знадобиться викликати метод `restore($identifier)`, де `$identifier` - це ключ, який ви зазначили у методі `store`. Cart::restore('username'); // To restore a cart instance named 'wishlist' Cart::instance('wishlist')->restore('username'); -### Merge the cart -If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items. +### Злиття кошика +Якщо ви хочете злити кошик із іншим у базі даних, вам знадобиться викликати метод `merge($identifier)`, де `$identifier` - це ключ, який ви зазначили у методі`store`. Ви також можете визначити чи хочете ви зберегти знижку і ставку оподаткування для товарів. // Merge the contents of 'savedcart' into 'username'. Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); -## 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: +Пакет Кошик (Cart) видаватиме винятки у разі, якщо щось відбувається не за планом. Таким чином, вам буде простіше відлагоджувати (debug) ваш код, використовуючи пакет Кошик, або обробляти помилку за типом винятку. Пакети Кошика (Cart) можуть видавати наступні вийнятки: -| Exception | Reason | +| Виняток | Пояснення | | ---------------------------- | ---------------------------------------------------------------------------------- | -| *CartAlreadyStoredException* | When trying to store a cart that was already stored using the specified identifier | -| *InvalidRowIDException* | When the rowId that got passed doesn't exists in the current cart instance | -| *UnknownModelException* | When you try to associate an none existing model to a CartItem. | +| *CartAlreadyStoredException* | ВинятокКошикВжеЗбережено Коли ви намагаєтеся зберегти кошик, який вже було збережено, застосовуючи вказаний ідентифікатор | +| *InvalidRowIDException* | ВинятокНеправильнийІдРядка Коли rowId, який було передано, не існує у поточному екземплярі кошика | +| *UnknownModelException* | ВинятокНевідомаМодель Коли ви намагаєтеся об'єднати неіснуючу модель до CartItem. | -## Events +## Події -The cart also has events build in. There are five events available for you to listen for. +Кошик також має вбудовані події. Існує п'ять подій, до яких варто прислухатися. -| Event | Fired | Parameter | +| Подія | Видано | Параметр | | ------------- | ---------------------------------------- | -------------------------------- | -| cart.added | When an item was added to the cart. | The `CartItem` that was added. | -| cart.updated | When an item in the cart was updated. | The `CartItem` that was updated. | -| 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.added | Коли товар додано до кошика. | `CartItem`, який було додано. | +| cart.updated | Коли товар оновлено у кошику. | `CartItem`, який було оновлено. | +| cart.removed | Коли товар вилучено з кошика. | `CartItem`, який було вилучено. | +| cart.stored | Коли вміст кошика було збережено. | - | +| cart.restored | Коли вміст кошика було відновлено. | - | -## Example +## Приклад -Below is a little example of how to list the cart content in a table: +Нижче невеликий приклад як відобразити вміст кошика у таблиці: ```php From 473de6429da48f64bfd002f814c411e3c760d1ba Mon Sep 17 00:00:00 2001 From: LucyIkonnikova-Skutsenia Date: Sat, 19 Oct 2019 00:43:18 +0300 Subject: [PATCH 21/52] Update README_uk-UA.md --- README_uk-UA.md | 58 ++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/README_uk-UA.md b/README_uk-UA.md index 9ea183a..4c835f1 100644 --- a/README_uk-UA.md +++ b/README_uk-UA.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -Цей репозиторій є відгалуженням [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) з додатковими незначними фічамиб сумісними з Laravel 6. +Цей репозиторій є відгалуженням [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) та містить додаткові незначні доповнення, сумісні з Laravel 6. ## Встановлення @@ -19,7 +19,7 @@ Тепер ви готові розпочати користуватися кошиком у вашому застосунку. -**Починаючи з версії 2 даного пакету з'явилася можливість впровадження залежності для впровадження екземплера класу Кошик (Cart) до вашого контролера або іншого класу** +**Починаючи з версії 2 даного пакету з'явилася можливість впровадження залежності для впровадження екземпляра класу Кошик (Cart) до вашого контролера або іншого класу** ## Огляд Щоб детальніше ознайомитися LaravelShoppingcart, можете пройти за посиланнями @@ -39,15 +39,15 @@ ### Cart::add() -Додавати покупки у кошик дуже зручно - достатньо лише скористатися методом `add()`, який приймає різноманітні параметри. +Додавати покупки у кошик дуже зручно - достатньо скористатися методом `add()`, який приймає різноманітні параметри. -У найпростішій формі метода достатньо вказати ідентифікатор, назву, кількість, ціну та вагу товару, який ви хочете додати у кошик. +У найпростішій формі метода достатньо вказати ідентифікатор товару, назву, кількість, ціну та вагу товару, який ви хочете додати у кошик. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550); ``` -У якості додаткового п'ятого параметра можна задати варіанти, наприклад, щоб додати декілька одиниць з однаковим ідентифікатором, але різного розміру. +У якості додаткового п'ятого параметра можна задати додаткові опції, наприклад, щоб додати декілька одиниць з однаковим ідентифікатором, але, наприклад, різного розміру. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); @@ -55,7 +55,7 @@ Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); **Метод `add()` повертає екземпляр CartItems того товару, який ви щойно додали у кошик.** -Можливо, вам більше до вподоби додавати товари, використовуючи масив? Якщо масив містить усі необхідні поля, ви можете передавати масив у цей метод. Поле із додатковими варіантами є необов'язковим. +Можливо, вам більше до вподоби додавати товари, використовуючи масив? Якщо масив містить усі необхідні поля, ви можете передавати масив у цей метод. Поле із додатковими опціями є необов'язковим. ```php Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); @@ -69,12 +69,12 @@ Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, ```php Cart::add($product, 1, ['size' => 'large']); ``` -У якості додаткового параметра, ви можете додати варіанти. +У якості додаткового параметра, ви можете внести опції. ```php Cart::add($product, 1, ['size' => 'large']); ``` -Нарешті, ви також можете додавати до кошика декілька одиниць водночас. Для цього потрібно передати у `add()` масив масивів або масив Покупні, і їх буде додано в кошик. +Нарешті, ви також можете додавати до кошика декілька одиниць водночас. Для цього потрібно передати у `add()` масив масивів або масив Buyables, і їх буде додано в кошик. **Під час додавання декількох одиниць товару в кошик, метод `add()` повертає масив CartItems.** @@ -93,7 +93,7 @@ Cart::add([$product1, $product2]); Щоб оновити товар у кошику, вам знадобиться ідентифікатор рядка (rowId) даного товару. Далі ви можете скористатися методом `update()` для того, щоб оновити його. -Якщо ви просто хочете оновити кількість товару, вам потрібно передати у метод `update()` rowId і оновлену кількість: +Якщо ви просто хочете оновити кількість товару, вам необхідно передати у метод `update()` rowId і оновлену кількість: ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -132,7 +132,7 @@ Cart::get($rowId); ### Cart::content() -Звісно, вам також може знадобитися отримати інформацію про вміст кошика. Для цього вам потрібно скористатися методом `content`. Такий метод повертає колекцію CartItems, ви можете перебирати вміст такої колекції і відобразити вміст кошика для ваших клієнтів. +Вам також може знадобитися можливість отримати інформацію про вміст кошика. Для цього вам потрібно скористатися методом `content`. Такий метод повертає колекцію CartItems, ви можете перебирати вміст такої колекції і відобразити вміст кошика для ваших клієнтів. ```php Cart::content(); @@ -329,7 +329,7 @@ $cart->setDiscount($rowId, 21); ### Buyable -Для зручності швидкого додавання товарів до кошика та їхнього автоматичної об'єднання, ваша модель повинна запустити інтерфейс `Buyable`. Ви можете застосовувати `CanBeBought` трейт для імплементації необхідних методів, але майте на увазі, що такі методи застосовуватимуть попередньо визначені поля у вашій моделі для необхідних значень. +Для зручного швидкого додавання товарів до кошика та їхнього автоматичного об'єднання, ваша модель повинна запустити інтерфейс `Buyable`. Ви можете застосовувати `CanBeBought` трейт для імплементації необхідних методів, але зверніть увагу, що такі методи застосовуватимуть попередньо визначені поля у вашій моделі для необхідних значень. ```php groupBy('id'); Ви можете встановити поточний екземпляр кошика через виклик `Cart::instance('newInstance')`. З цього моменту, активний екземляр кошика буде `newInstance`, тому коли ви додаєте, вилучаєте або отримуєте інформацію щодо вмісту кошика, ви працюєте з екземпляром `newInstance` кошика. Якщо ви хочете переключитися між екзмеплярами, ви можете викликати `Cart::instance('otherInstance')` ще раз, і ви знову працюватимете з `otherInstance`. -Невеликий приклад: +Короткий приклад: ```php Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); @@ -424,7 +424,7 @@ Cart::instance('shopping')->content(); Cart::instance('wishlist')->count(); ``` -Ви також можете використати Контракт `InstanceIdentifier` для розширення бажаної моделі можливістю призначення / створення екземпляру Кошика (Cart) для неї. Така дія також дозволить напряму встановлювати глобальну знижку. +Ви також можете застосувати Контракт `InstanceIdentifier` для розширення бажаної моделі через призначення / створення екземпляру Кошика (Cart) для неї. Така дія також дозволить напряму встановлювати глобальну знижку. ``` restore('username'); -### Злиття кошика -Якщо ви хочете злити кошик із іншим у базі даних, вам знадобиться викликати метод `merge($identifier)`, де `$identifier` - це ключ, який ви зазначили у методі`store`. Ви також можете визначити чи хочете ви зберегти знижку і ставку оподаткування для товарів. +### Злиття кошиків +Якщо ви хочете злити кошик із іншим кошиком, збереженим у базі даних, вам знадобиться викликати метод `merge($identifier)`, де `$identifier` - це ключ, який ви зазначили у методі`store`. Ви також можете визначити чи хочете ви зберегти знижку і ставку оподаткування для товарів. // Merge the contents of 'savedcart' into 'username'. Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); -## Винятки +## Перехоплення -Пакет Кошик (Cart) видаватиме винятки у разі, якщо щось відбувається не за планом. Таким чином, вам буде простіше відлагоджувати (debug) ваш код, використовуючи пакет Кошик, або обробляти помилку за типом винятку. Пакети Кошика (Cart) можуть видавати наступні вийнятки: +Пакет Кошик (Cart) видаватиме винятки/перехоплення у разі, якщо щось йде не за планом. Таким чином, вам буде простіше відлагоджувати (debug) ваш код, використовуючи пакет Кошик, або обробляти помилку за типом перехоплення. Пакети Кошика можуть видавати наступні перехоплення: -| Виняток | Пояснення | +| Перехоплення | Пояснення | | ---------------------------- | ---------------------------------------------------------------------------------- | -| *CartAlreadyStoredException* | ВинятокКошикВжеЗбережено Коли ви намагаєтеся зберегти кошик, який вже було збережено, застосовуючи вказаний ідентифікатор | -| *InvalidRowIDException* | ВинятокНеправильнийІдРядка Коли rowId, який було передано, не існує у поточному екземплярі кошика | -| *UnknownModelException* | ВинятокНевідомаМодель Коли ви намагаєтеся об'єднати неіснуючу модель до CartItem. | +| *CartAlreadyStoredException* | ПерехопленняКошикВжеЗбережено Коли ви намагаєтеся зберегти кошик, який вже було збережено, застосовуючи вказаний ідентифікатор | +| *InvalidRowIDException* | ПерехопленняНеправильнийІдРядка Коли rowId, який було передано, не існує у поточному екземплярі кошика | +| *UnknownModelException* | ПерехопленняНевідомаМодель Коли ви намагаєтеся об'єднати неіснуючу модель з CartItem. | ## Події -Кошик також має вбудовані події. Існує п'ять подій, до яких варто прислухатися. +Кошик також має вбудовані події. Існує п'ять подій, які можна очікувати. | Подія | Видано | Параметр | | ------------- | ---------------------------------------- | -------------------------------- | @@ -568,7 +568,7 @@ foreach(Cart::content() as $row) { ## Приклад -Нижче невеликий приклад як відобразити вміст кошика у таблиці: +Нижче наведено приклад як відобразити вміст кошика у таблиці: ```php From f31c153e3e6a4898b9498d412be39086086d2e3b Mon Sep 17 00:00:00 2001 From: Cristian Date: Mon, 21 Oct 2019 19:00:34 +0200 Subject: [PATCH 22/52] Update CartItem.php weight variable in if block --- src/CartItem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CartItem.php b/src/CartItem.php index 5a49ef2..667bedc 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -98,7 +98,7 @@ class CartItem implements Arrayable, Jsonable if (strlen($price) < 0 || !is_numeric($price)) { throw new \InvalidArgumentException('Please supply a valid price.'); } - if (strlen($price) < 0 || !is_numeric($weight)) { + if (strlen($weight) < 0 || !is_numeric($weight)) { throw new \InvalidArgumentException('Please supply a valid weight.'); } From d0cf5d7ab0a26ed7fc0eb9239d4a96ece2867d8a Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Mon, 21 Oct 2019 19:52:03 +0200 Subject: [PATCH 23/52] Corrected PHPDoc --- src/CartItem.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CartItem.php b/src/CartItem.php index 667bedc..5efb546 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -85,6 +85,7 @@ class CartItem implements Arrayable, Jsonable * @param int|string $id * @param string $name * @param float $price + * @param float $weight * @param array $options */ public function __construct($id, $name, $price, $weight = 0, array $options = []) From 819d7de5af7a1f11d3c90b860213b2d40de4e9d7 Mon Sep 17 00:00:00 2001 From: tiotobing <33707075+tiotobing@users.noreply.github.com> Date: Fri, 25 Oct 2019 14:28:11 +0700 Subject: [PATCH 24/52] Update README_Ind.md Add Description in Indonesian language, Code Ind/ID --- README.md | 233 +++++++++++++++++++++++++++--------------------------- 1 file changed, 117 insertions(+), 116 deletions(-) diff --git a/README.md b/README.md index 3481422..67a3fab 100644 --- a/README.md +++ b/README.md @@ -7,22 +7,22 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. +Ini adalah percabangan dari [Crisane's LaravelShoppingcart] (https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 -## Installation +## Instalasi -Install the [package](https://packagist.org/packages/bumbummen99/shoppingcart) through [Composer](http://getcomposer.org/). +Install paket(https://packagist.org/packages/bumbummen99/shoppingcart) menggunakan [Composer](http://getcomposer.org/). -Run the Composer require command from the Terminal: +Jalankan Composer dengan menggunakan perintah berikut: composer require bumbummen99/shoppingcart -Now you're ready to start using the shoppingcart in your application. +Sekarang Anda siap untuk mulai menggunakan shoppingcart di aplikasi Anda. -**As of version 2 of this package it's possibly to use dependency injection to inject an instance of the Cart class into your controller or other class** +**Pada versi 2 dari paket ini memungkinkan untuk menggunakan injeksi dependensi untuk memasukkan instance Class Cart ke controller Anda atau Class lain** -## Overview -Look at one of the following topics to learn more about LaravelShoppingcart +## Gambaran +Lihat salah satu topik berikut untuk mempelajari lebih lanjut tentang LaravelShoppingcart * [Usage](#usage) * [Collections](#collections) @@ -33,51 +33,51 @@ Look at one of the following topics to learn more about LaravelShoppingcart * [Events](#events) * [Example](#example) -## Usage +## Penggunaan -The shoppingcart gives you the following methods to use: +Shoppingcart memberi Anda metode berikut untuk digunakan: ### Cart::add() -Adding an item to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters. +Menambahkan item ke troli sangat sederhana, Anda cukup menggunakan metode `add ()`, yang menerima berbagai parameter. -In its most basic form you can specify the id, name, quantity, price and weight of the product you'd like to add to the cart. +Dalam bentuknya yang paling mendasar, Anda dapat menentukan id, nama, jumlah, harga, dan berat produk yang ingin Anda tambahkan ke troli. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550); ``` -As an optional fifth parameter you can pass it options, so you can add multiple items with the same id, but with (for instance) a different size. +Sebagai opsional parameter kelima, Anda dapat memberikan opsi, sehingga Anda dapat menambahkan beberapa item dengan id yang sama, tetapi dengan (instance) ukuran yang berbeda. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); ``` -**The `add()` method will return an CartItem instance of the item you just added to the cart.** +**Metode `add ()` akan mengembalikan instance CartItem dari item yang baru saja Anda tambahkan ke troli.** -Maybe you prefer to add the item using an array? As long as the array contains the required keys, you can pass it to the method. The options key is optional. +Mungkin Anda lebih suka menambahkan item menggunakan array? Selama array berisi kunci yang diperlukan, Anda bisa meneruskannya ke metode. Tombol opsi adalah opsional. ```php Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); ``` -New in version 2 of the package is the possibility to work with the [Buyable](#buyable) interface. The way this works is that you have a model implement the [Buyable](#buyable) interface, which will make you implement a few methods so the package knows how to get the id, name and price from your model. -This way you can just pass the `add()` method a model and the quantity and it will automatically add it to the cart. +Baru dalam versi 2 paket ini adalah kemungkinan untuk bekerja dengan antarmuka [Buyable] (#buyable). Cara kerjanya adalah bahwa Anda memiliki model yang mengimplementasikan antarmuka [Buyable] (#buyable), yang akan membuat Anda menerapkan beberapa metode sehingga paket tahu bagaimana cara mendapatkan id, nama, dan harga dari model Anda. +Dengan cara ini Anda bisa meneruskan metode `add ()` model dan kuantitas dan secara otomatis akan menambahkannya ke troli. -**As an added bonus it will automatically associate the model with the CartItem** +**Sebagai bonus tambahan, itu akan secara otomatis mengaitkan model dengan CartItem** ```php Cart::add($product, 1, ['size' => 'large']); ``` -As an optional third parameter you can add options. +Sebagai parameter ketiga opsional, Anda dapat menambahkan opsi. ```php Cart::add($product, 1, ['size' => 'large']); ``` -Finally, you can also add multipe items to the cart at once. -You can just pass the `add()` method an array of arrays, or an array of Buyables and they will be added to the cart. +Terakhir, Anda juga dapat menambahkan banyak item ke troli sekaligus. +Anda bisa meneruskan metode `add ()` sebuah array array, atau array yang dapat dibeli dan mereka akan ditambahkan ke troli. -**When adding multiple items to the cart, the `add()` method will return an array of CartItems.** +**Saat menambahkan beberapa item ke troli, metode `add ()` akan mengembalikan array CartItems.** ```php Cart::add([ @@ -91,18 +91,17 @@ Cart::add([$product1, $product2]); ### Cart::update() -To update an item in the cart, you'll first need the rowId of the item. -Next you can use the `update()` method to update it. +Untuk memperbarui item di troli, Anda harus terlebih dahulu membutuhkan rowId item. +Selanjutnya Anda dapat menggunakan metode `update ()` untuk memperbaruinya. -If you simply want to update the quantity, you'll pass the update method the rowId and the new quantity: +Jika Anda hanya ingin memperbarui kuantitas, Anda akan melewati metode pembaruan rowId dan kuantitas baru: ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::update($rowId, 2); // Will update the quantity ``` - -If you want to update more attributes of the item, you can either pass the update method an array or a `Buyable` as the second parameter. This way you can update all information of the item with the given rowId. +Jika Anda ingin memperbarui lebih banyak atribut dari item, Anda dapat melewati metode pembaruan array atau `Dapat Dibeli` sebagai parameter kedua. Dengan cara ini Anda dapat memperbarui semua informasi item dengan rowId yang diberikan. ```php Cart::update($rowId, ['name' => 'Product 1']); // Will update the name @@ -113,7 +112,7 @@ Cart::update($rowId, $product); // Will update the id, name and price ### Cart::remove() -To remove an item for the cart, you'll again need the rowId. This rowId you simply pass to the `remove()` method and it will remove the item from the cart. +Untuk menghapus item untuk keranjang, Anda akan membutuhkan rowId lagi. Baris ini. Apakah Anda hanya meneruskan ke metode `hapus ()` dan itu akan menghapus item dari keranjang. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -123,7 +122,7 @@ Cart::remove($rowId); ### Cart::get() -If you want to get an item from the cart using its rowId, you can simply call the `get()` method on the cart and pass it the rowId. +Jika Anda ingin mendapatkan item dari troli menggunakan rowId-nya, Anda bisa memanggil metode `get ()` di troli dan meneruskannya dengan rowId. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -133,13 +132,12 @@ Cart::get($rowId); ### Cart::content() -Of course you also want to get the carts content. This is where you'll use the `content` method. This method will return a Collection of CartItems which you can iterate over and show the content to your customers. +Tentu saja Anda juga ingin mendapatkan konten gerobak. Di sinilah Anda akan menggunakan metode `konten`. Metode ini akan mengembalikan Koleksi CartItems yang dapat Anda ulangi dan tampilkan kontennya kepada pelanggan Anda. ```php Cart::content(); ``` - -This method will return the content of the current cart instance, if you want the content of another instance, simply chain the calls. +Metode ini akan mengembalikan konten instance keranjang saat ini, jika Anda ingin konten instance lain, cukup lakukan panggilan. ```php Cart::instance('wishlist')->content(); @@ -147,7 +145,7 @@ Cart::instance('wishlist')->content(); ### Cart::destroy() -If you want to completely remove the content of a cart, you can call the destroy method on the cart. This will remove all CartItems from the cart for the current cart instance. +Jika Anda ingin menghapus konten keranjang sepenuhnya, Anda dapat memanggil metode penghancuran di kereta. Ini akan menghapus semua CartItems dari troli untuk instance troli saat ini. ```php Cart::destroy(); @@ -155,115 +153,117 @@ Cart::destroy(); ### Cart::weight() -The `weight()` method can be used to get the weight total of all items in the cart, given there weight and quantity. +Metode `weight ()` dapat digunakan untuk mendapatkan total berat semua item di troli, mengingat berat dan kuantitasnya. + ```php Cart::weight(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::weight($decimals, $decimalSeperator, $thousandSeperator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->weight`** +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> weight`** ### Cart::total() -The `total()` method can be used to get the calculated total of all items in the cart, given there price and quantity. +Maka `total ()` dapat digunakan untuk mendapatkan total yang dihitung dari semua item dalam troli, mengingat ada harga dan kuantitas. ```php Cart::total(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::total($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->total`** + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> total`** ### Cart::tax() -The `tax()` method can be used to get the calculated amount of tax for all items in the cart, given there price and quantity. +Maka `tax ()` dapat digunakan untuk mendapatkan jumlah pajak yang dihitung untuk semua item di troli, mengingat ada harga dan kuantitas. ```php Cart::tax(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::tax($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the tax property `$cart->tax`** +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> tax`** ### Cart::subtotal() -The `subtotal()` method can be used to get the total of all items in the cart, minus the total amount of tax. +Maka `subtotal ()` dapat digunakan untuk mendapatkan total semua item dalam troli, dikurangi jumlah total pajak. ```php Cart::subtotal(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::subtotal($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->subtotal`** +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> subtotal`** ### Cart::discount() -The `discount()` method can be used to get the total discount of all items in the cart. +Maka `diskon ()` dapat digunakan untuk mendapatkan diskon total semua item di troli. ```php Cart::discount(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::discount($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->discount`** +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> discount`** ### Cart::initial() -The `initial()` method can be used to get the total price of all items in the cart before discount. +maka `initial ()` dapat digunakan untuk mendapatkan harga total semua item di troli sebelum diskon. ```php Cart::initial(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional ```php Cart::initial($decimals, $decimalSeparator, $thousandSeparator); ``` -You can set the default number format in the config file. +Anda dapat mengatur format angka default dalam file konfigurasi. -**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->initial`** +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> initial`** ### Cart::count() -If you want to know how many items there are in your cart, you can use the `count()` method. This method will return the total number of items in the cart. So if you've added 2 books and 1 shirt, it will return 3 items. +Jika Anda ingin tahu berapa banyak item yang ada di troli Anda, Anda dapat menggunakan metode `count ()`. Metode ini akan mengembalikan jumlah total barang dalam kereta. Jadi, jika Anda telah menambahkan 2 buku dan 1 kemeja, itu akan mengembalikan 3 item. ```php Cart::count(); @@ -272,13 +272,13 @@ $cart->count(); ### Cart::search() -To find an item in the cart, you can use the `search()` method. +Untuk menemukan item di troli, Anda dapat menggunakan metode `search ()`. -**This method was changed on version 2** +**Metode ini diubah pada versi 2** -Behind the scenes, the method simply uses the filter method of the Laravel Collection class. This means you must pass it a Closure in which you'll specify you search terms. +Di belakang layar, metode ini hanya menggunakan metode filter dari kelas Laravel Collection. Ini berarti Anda harus memberikannya suatu Penutupan di mana Anda akan menentukan istilah pencarian Anda. -If you for instance want to find all items with an id of 1: +Jika Anda misalnya ingin menemukan semua item dengan id 1: ```php $cart->search(function ($cartItem, $rowId) { @@ -286,15 +286,15 @@ $cart->search(function ($cartItem, $rowId) { }); ``` -As you can see the Closure will receive two parameters. The first is the CartItem to perform the check against. The second parameter is the rowId of this CartItem. +Seperti yang Anda lihat, Penutupan akan menerima dua parameter. Yang pertama adalah Item Keranjang untuk melakukan pemeriksaan terhadap. Parameter kedua adalah rowId dari CartItem ini. -**The method will return a Collection containing all CartItems that where found** +** Metode ini akan mengembalikan Koleksi yang berisi semua CartItems yang ditemukan ** -This way of searching gives you total control over the search process and gives you the ability to create very precise and specific searches. +Cara pencarian ini memberi Anda kontrol total atas proses pencarian dan memberi Anda kemampuan untuk membuat pencarian yang sangat tepat dan spesifik. -### Cart::setTax($rowId, $taxRate) +### Cart :: setTax ($ rowId, $ taxRate) -You can use the `setTax()` method to change the tax rate that applies to the CartItem. This will overwrite the value set in the config file. +Anda dapat menggunakan metode `setTax ()` untuk mengubah tarif pajak yang berlaku untuk CartItem. Ini akan menimpa nilai yang ditetapkan dalam file konfigurasi. ```php Cart::setTax($rowId, 21); @@ -303,7 +303,7 @@ $cart->setTax($rowId, 21); ### Cart::setGlobalTax($taxRate) -You can use the `setGlobalTax()` method to change the tax rate for all items in the cart. New items will receive the setGlobalTax as well. +Anda dapat menggunakan metode `setGlobalTax ()` untuk mengubah tarif pajak untuk semua item di troli. Item baru juga akan menerima setGlobalTax. ```php Cart::setGlobalTax(21); @@ -312,7 +312,7 @@ $cart->setGlobalTax(21); ### Cart::setGlobalDiscount($discountRate) -You can use the `setGlobalDiscount()` method to change the discount rate for all items in the cart. New items will receive the discount as well. +Anda dapat menggunakan metode `setGlobalDiscount ()` untuk mengubah tingkat diskonto untuk semua item di troli. Barang baru akan menerima diskon juga. ```php Cart::setGlobalDiscount(50); @@ -321,7 +321,7 @@ $cart->setGlobalDiscount(50); ### Cart::setDiscount($rowId, $taxRate) -You can use the `setDiscount()` method to change the discount rate that applies a CartItem. Keep in mind that this value will be changed if you set the global discount for the Cart afterwards. +Anda dapat menggunakan metode `setDiscount ()` untuk mengubah tingkat diskonto yang menerapkan CartItem. Perlu diingat bahwa nilai ini akan berubah jika Anda menetapkan diskon global untuk Keranjang sesudahnya. ```php Cart::setDiscount($rowId, 21); @@ -330,7 +330,8 @@ $cart->setDiscount($rowId, 21); ### Buyable -For the convenience of faster adding items to cart and their automatic association, your model has to implement the `Buyable` interface. You can use the `CanBeBought` trait to implement the required methods but keep in mind that these will use predefined fields on your model for the required values. +Untuk kenyamanan menambahkan item yang lebih cepat ke troli dan asosiasi otomatisnya, model Anda harus mengimplementasikan antarmuka `Dapat Dibeli` Anda dapat menggunakan sifat `CanBeBought` untuk mengimplementasikan metode yang diperlukan tetapi perlu diingat bahwa ini akan menggunakan bidang yang telah ditentukan pada model Anda untuk nilai yang diperlukan. + ```php count(); ``` -Or you can group the content by the id of the products: +Atau Anda dapat mengelompokkan konten berdasarkan id produk: ```php Cart::content()->groupBy('id'); @@ -400,12 +401,12 @@ Cart::content()->groupBy('id'); ## Instances -The packages supports multiple instances of the cart. The way this works is like this: +Paket-paket mendukung beberapa instance dari kereta. Cara kerjanya seperti ini: -You can set the current instance of the cart by calling `Cart::instance('newInstance')`. From this moment, the active instance of the cart will be `newInstance`, so when you add, remove or get the content of the cart, you're work with the `newInstance` instance of the cart. -If you want to switch instances, you just call `Cart::instance('otherInstance')` again, and you're working with the `otherInstance` again. +Anda dapat mengatur instance keranjang saat ini dengan memanggil `Cart :: instance ('newInstance')`. Mulai saat ini, instance aktif dari cart adalah `newInstance`, jadi ketika Anda menambah, menghapus, atau mendapatkan konten dari cart, Anda bekerja dengan instance` newInstance` dari cart. +Jika Anda ingin mengganti instance, Anda cukup memanggil `Cart :: instance ('otherInstance')` lagi, dan Anda bekerja dengan `otherInstance` lagi. -So a little example: +Contoh Kecil: ```php Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); @@ -425,7 +426,7 @@ Cart::instance('shopping')->content(); Cart::instance('wishlist')->count(); ``` -You can also use the `InstanceIdentifier` Contract to extend a desired Model to assign / create a Cart instance for it. This also allows to directly set the global discount. +Anda juga dapat menggunakan Kontrak `InstanceIdentifier` untuk memperpanjang Model yang diinginkan untuk menetapkan / membuat instance Cart untuknya. Ini juga memungkinkan untuk secara langsung mengatur diskon global. ``` content()`.** +**N.B.2 Contoh cart default disebut `default`, jadi ketika Anda tidak menggunakan instance,` Cart :: konten (); `sama dengan` Cart :: instance ('default') -> konten () `.** ## Models -Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. Let's say you have a `Product` model in your application. With the `associate()` method, you can tell the cart that an item in the cart, is associated to the `Product` model. +Karena sangat nyaman untuk dapat secara langsung mengakses model dari CartItem, apakah mungkin untuk mengaitkan model dengan barang-barang di dalam kereta. Katakanlah Anda memiliki model `Produk` di aplikasi Anda. Dengan metode `associate ()`, Anda dapat memberi tahu troli bahwa item di troli, terkait dengan model `Product`. -That way you can access your model right from the `CartItem`! +Dengan begitu Anda dapat mengakses model Anda langsung dari `CartItem`! -The model can be accessed via the `model` property on the CartItem. +Model ini dapat diakses melalui properti `model` di CartItem. -**If your model implements the `Buyable` interface and you used your model to add the item to the cart, it will associate automatically.** +**Jika model Anda mengimplementasikan antarmuka `Buy Able` dan Anda menggunakan model Anda untuk menambahkan item ke troli, itu akan dikaitkan secara otomatis.** -Here is an example: +Berikut adalah contoh: ```php @@ -508,76 +509,76 @@ foreach(Cart::content() as $row) { - [Storing the cart](#storing-the-cart) - [Restoring the cart](#restoring-the-cart) -### Configuration -To save cart into the database so you can retrieve it later, the package needs to know which database connection to use and what the name of the table is. -By default the package will use the default database connection and use a table named `shoppingcart`. -If you want to change these options, you'll have to publish the `config` file. +### Konfigurasi +Untuk menyimpan keranjang ke dalam basis data sehingga Anda dapat mengambilnya nanti, paket perlu mengetahui koneksi basis data yang digunakan dan apa nama tabelnya. +Secara default paket akan menggunakan koneksi database default dan menggunakan tabel bernama `shoppingcart`. +Jika Anda ingin mengubah opsi ini, Anda harus menerbitkan file `config`. php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config" -This will give you a `cart.php` config file in which you can make the changes. +Ini akan memberi Anda file konfigurasi `cart.php` di mana Anda dapat melakukan perubahan. -To make your life easy, the package also includes a ready to use `migration` which you can publish by running: +Untuk memudahkan hidup Anda, paket ini juga menyertakan `migration` yang siap digunakan yang dapat Anda terbitkan dengan menjalankan: php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations" -This will place a `shoppingcart` table's migration file into `database/migrations` directory. Now all you have to do is run `php artisan migrate` to migrate your database. +Ini akan menempatkan file migrasi tabel `shoppingcart` ke direktori` database / migrations`. Sekarang yang harus Anda lakukan adalah menjalankan `php artisan migrate` untuk memigrasi basis data Anda. -### Storing the cart -To store your cart instance into the database, you have to call the `store($identifier) ` method. Where `$identifier` is a random key, for instance the id or username of the user. +### Menyimpan ke Troli +Untuk menyimpan instance kereta ke dalam database, Anda harus memanggil metode `store ($ identifier)`. Di mana `$ identifier` adalah kunci acak, misalnya id atau nama pengguna pengguna. Cart::store('username'); // To store a cart instance named 'wishlist' Cart::instance('wishlist')->store('username'); -### Restoring the cart -If you want to retrieve the cart from the database and restore it, all you have to do is call the `restore($identifier)` where `$identifier` is the key you specified for the `store` method. +### Mengembalikan ke Troli +Jika Anda ingin mengambil keranjang dari database dan mengembalikannya, yang harus Anda lakukan adalah memanggil `restore ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. Cart::restore('username'); // To restore a cart instance named 'wishlist' Cart::instance('wishlist')->restore('username'); -### Merge the cart -If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items. +### Menggabungkan Troli +Jika Anda ingin menggabungkan keranjang dengan keranjang lain dari basis data, yang harus Anda lakukan adalah memanggil `gabungan ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. Anda juga dapat menentukan apakah Anda ingin mempertahankan potongan harga dan tarif pajak item. // Merge the contents of 'savedcart' into 'username'. Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); -## Exceptions +## Pengecualian -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: +Paket Cart akan mengeluarkan pengecualian jika terjadi kesalahan. Dengan cara ini lebih mudah untuk men-debug kode Anda menggunakan paket Cart atau untuk menangani kesalahan berdasarkan pada jenis pengecualian. Paket-paket Cart dapat membuang pengecualian berikut: | Exception | Reason | | ---------------------------- | ---------------------------------------------------------------------------------- | -| *CartAlreadyStoredException* | When trying to store a cart that was already stored using the specified identifier | -| *InvalidRowIDException* | When the rowId that got passed doesn't exists in the current cart instance | -| *UnknownModelException* | When you try to associate an none existing model to a CartItem. | +| *CartAlreadyStoredException* | Saat mencoba menyimpan keranjang yang sudah disimpan menggunakan pengenal yang ditentukan | +| *InvalidRowIDException* | Ketika rowId yang diteruskan tidak ada dalam instance troli saat ini | +| *UnknownModelException* | Saat Anda mencoba mengaitkan model yang tidak ada dengan Item Keranjang. | ## Events -The cart also has events build in. There are five events available for you to listen for. +Troli juga memiliki event. Ada lima event yang bisa Anda lakukan. | Event | Fired | Parameter | | ------------- | ---------------------------------------- | -------------------------------- | -| cart.added | When an item was added to the cart. | The `CartItem` that was added. | -| cart.updated | When an item in the cart was updated. | The `CartItem` that was updated. | -| 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.added | Saat item ditambahkan ke troli. | The `CartItem` that was added. | +| cart.updated | Ketika item dalam troli diperbarui. | The `CartItem` that was updated. | +| cart.removed | Ketika item dalam troli dihapus. | The `CartItem` that was removed. | +| cart.stored | Ketika isi trol disimpan. | - | +| cart.restored | Ketika konten keranjang Dikembalikan. | - | -## Example +## Contoh -Below is a little example of how to list the cart content in a table: +Di bawah ini adalah sedikit contoh cara membuat daftar isi keranjang dalam sebuah tabel: ```php -// Add some items in your Controller. +// Tambahkan beberapa item di Kontroler Anda. Cart::add('192ao12', 'Product 1', 1, 9.99); Cart::add('1239ad0', 'Product 2', 2, 5.95, ['size' => 'large']); -// Display the content in a View. +// Tampilkan konten dalam Tampilan. From 8a9a5066593ca565093c46fd28f2b3f3bb24589b Mon Sep 17 00:00:00 2001 From: tiotobing <33707075+tiotobing@users.noreply.github.com> Date: Thu, 31 Oct 2019 11:09:03 +0700 Subject: [PATCH 25/52] Create README_Idn.md add descriptions in Indonesian languange, Code Idn/ID --- README_Idn.md | 628 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 628 insertions(+) create mode 100644 README_Idn.md diff --git a/README_Idn.md b/README_Idn.md new file mode 100644 index 0000000..67a3fab --- /dev/null +++ b/README_Idn.md @@ -0,0 +1,628 @@ +## LaravelShoppingcart +[![Build Status](https://travis-ci.org/bumbummen99/LaravelShoppingcart.png?branch=master)](https://travis-ci.org/bumbummen99/LaravelShoppingcart) +[![codecov](https://codecov.io/gh/bumbummen99/LaravelShoppingcart/branch/master/graph/badge.svg)](https://codecov.io/gh/bumbummen99/LaravelShoppingcart) +[![StyleCI](https://styleci.io/repos/152610878/shield?branch=master)](https://styleci.io/repos/152610878) +[![Total Downloads](https://poser.pugx.org/bumbummen99/shoppingcart/downloads.png)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![Latest Stable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/stable)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) +[![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) + +Ini adalah percabangan dari [Crisane's LaravelShoppingcart] (https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 + +## Instalasi + +Install paket(https://packagist.org/packages/bumbummen99/shoppingcart) menggunakan [Composer](http://getcomposer.org/). + +Jalankan Composer dengan menggunakan perintah berikut: + + composer require bumbummen99/shoppingcart + +Sekarang Anda siap untuk mulai menggunakan shoppingcart di aplikasi Anda. + +**Pada versi 2 dari paket ini memungkinkan untuk menggunakan injeksi dependensi untuk memasukkan instance Class Cart ke controller Anda atau Class lain** + +## Gambaran +Lihat salah satu topik berikut untuk mempelajari lebih lanjut tentang LaravelShoppingcart + +* [Usage](#usage) +* [Collections](#collections) +* [Instances](#instances) +* [Models](#models) +* [Database](#database) +* [Exceptions](#exceptions) +* [Events](#events) +* [Example](#example) + +## Penggunaan + +Shoppingcart memberi Anda metode berikut untuk digunakan: + +### Cart::add() + +Menambahkan item ke troli sangat sederhana, Anda cukup menggunakan metode `add ()`, yang menerima berbagai parameter. + +Dalam bentuknya yang paling mendasar, Anda dapat menentukan id, nama, jumlah, harga, dan berat produk yang ingin Anda tambahkan ke troli. + +```php +Cart::add('293ad', 'Product 1', 1, 9.99, 550); +``` + +Sebagai opsional parameter kelima, Anda dapat memberikan opsi, sehingga Anda dapat menambahkan beberapa item dengan id yang sama, tetapi dengan (instance) ukuran yang berbeda. + +```php +Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); +``` + +**Metode `add ()` akan mengembalikan instance CartItem dari item yang baru saja Anda tambahkan ke troli.** + +Mungkin Anda lebih suka menambahkan item menggunakan array? Selama array berisi kunci yang diperlukan, Anda bisa meneruskannya ke metode. Tombol opsi adalah opsional. + +```php +Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); +``` + +Baru dalam versi 2 paket ini adalah kemungkinan untuk bekerja dengan antarmuka [Buyable] (#buyable). Cara kerjanya adalah bahwa Anda memiliki model yang mengimplementasikan antarmuka [Buyable] (#buyable), yang akan membuat Anda menerapkan beberapa metode sehingga paket tahu bagaimana cara mendapatkan id, nama, dan harga dari model Anda. +Dengan cara ini Anda bisa meneruskan metode `add ()` model dan kuantitas dan secara otomatis akan menambahkannya ke troli. + +**Sebagai bonus tambahan, itu akan secara otomatis mengaitkan model dengan CartItem** + +```php +Cart::add($product, 1, ['size' => 'large']); +``` +Sebagai parameter ketiga opsional, Anda dapat menambahkan opsi. +```php +Cart::add($product, 1, ['size' => 'large']); +``` + +Terakhir, Anda juga dapat menambahkan banyak item ke troli sekaligus. +Anda bisa meneruskan metode `add ()` sebuah array array, atau array yang dapat dibeli dan mereka akan ditambahkan ke troli. + +**Saat menambahkan beberapa item ke troli, metode `add ()` akan mengembalikan array CartItems.** + +```php +Cart::add([ + ['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 10.00, 'weight' => 550], + ['id' => '4832k', 'name' => 'Product 2', 'qty' => 1, 'price' => 10.00, 'weight' => 550, 'options' => ['size' => 'large']] +]); + +Cart::add([$product1, $product2]); + +``` + +### Cart::update() + +Untuk memperbarui item di troli, Anda harus terlebih dahulu membutuhkan rowId item. +Selanjutnya Anda dapat menggunakan metode `update ()` untuk memperbaruinya. + +Jika Anda hanya ingin memperbarui kuantitas, Anda akan melewati metode pembaruan rowId dan kuantitas baru: + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::update($rowId, 2); // Will update the quantity +``` +Jika Anda ingin memperbarui lebih banyak atribut dari item, Anda dapat melewati metode pembaruan array atau `Dapat Dibeli` sebagai parameter kedua. Dengan cara ini Anda dapat memperbarui semua informasi item dengan rowId yang diberikan. + +```php +Cart::update($rowId, ['name' => 'Product 1']); // Will update the name + +Cart::update($rowId, $product); // Will update the id, name and price + +``` + +### Cart::remove() + +Untuk menghapus item untuk keranjang, Anda akan membutuhkan rowId lagi. Baris ini. Apakah Anda hanya meneruskan ke metode `hapus ()` dan itu akan menghapus item dari keranjang. + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::remove($rowId); +``` + +### Cart::get() + +Jika Anda ingin mendapatkan item dari troli menggunakan rowId-nya, Anda bisa memanggil metode `get ()` di troli dan meneruskannya dengan rowId. + +```php +$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; + +Cart::get($rowId); +``` + +### Cart::content() + +Tentu saja Anda juga ingin mendapatkan konten gerobak. Di sinilah Anda akan menggunakan metode `konten`. Metode ini akan mengembalikan Koleksi CartItems yang dapat Anda ulangi dan tampilkan kontennya kepada pelanggan Anda. + +```php +Cart::content(); +``` +Metode ini akan mengembalikan konten instance keranjang saat ini, jika Anda ingin konten instance lain, cukup lakukan panggilan. + +```php +Cart::instance('wishlist')->content(); +``` + +### Cart::destroy() + +Jika Anda ingin menghapus konten keranjang sepenuhnya, Anda dapat memanggil metode penghancuran di kereta. Ini akan menghapus semua CartItems dari troli untuk instance troli saat ini. + +```php +Cart::destroy(); +``` + +### Cart::weight() + +Metode `weight ()` dapat digunakan untuk mendapatkan total berat semua item di troli, mengingat berat dan kuantitasnya. + + +```php +Cart::weight(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::weight($decimals, $decimalSeperator, $thousandSeperator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> weight`** + +### Cart::total() + +Maka `total ()` dapat digunakan untuk mendapatkan total yang dihitung dari semua item dalam troli, mengingat ada harga dan kuantitas. + +```php +Cart::total(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::total($decimals, $decimalSeparator, $thousandSeparator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> total`** + +### Cart::tax() + +Maka `tax ()` dapat digunakan untuk mendapatkan jumlah pajak yang dihitung untuk semua item di troli, mengingat ada harga dan kuantitas. + +```php +Cart::tax(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::tax($decimals, $decimalSeparator, $thousandSeparator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> tax`** + +### Cart::subtotal() + +Maka `subtotal ()` dapat digunakan untuk mendapatkan total semua item dalam troli, dikurangi jumlah total pajak. + +```php +Cart::subtotal(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::subtotal($decimals, $decimalSeparator, $thousandSeparator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> subtotal`** + +### Cart::discount() + +Maka `diskon ()` dapat digunakan untuk mendapatkan diskon total semua item di troli. + +```php +Cart::discount(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::discount($decimals, $decimalSeparator, $thousandSeparator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> discount`** + +### Cart::initial() + +maka `initial ()` dapat digunakan untuk mendapatkan harga total semua item di troli sebelum diskon. + +```php +Cart::initial(); +``` + +Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional + +```php +Cart::initial($decimals, $decimalSeparator, $thousandSeparator); +``` + +Anda dapat mengatur format angka default dalam file konfigurasi. + +**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> initial`** + +### Cart::count() + +Jika Anda ingin tahu berapa banyak item yang ada di troli Anda, Anda dapat menggunakan metode `count ()`. Metode ini akan mengembalikan jumlah total barang dalam kereta. Jadi, jika Anda telah menambahkan 2 buku dan 1 kemeja, itu akan mengembalikan 3 item. + +```php +Cart::count(); +$cart->count(); +``` + +### Cart::search() + +Untuk menemukan item di troli, Anda dapat menggunakan metode `search ()`. + +**Metode ini diubah pada versi 2** + +Di belakang layar, metode ini hanya menggunakan metode filter dari kelas Laravel Collection. Ini berarti Anda harus memberikannya suatu Penutupan di mana Anda akan menentukan istilah pencarian Anda. + +Jika Anda misalnya ingin menemukan semua item dengan id 1: + +```php +$cart->search(function ($cartItem, $rowId) { + return $cartItem->id === 1; +}); +``` + +Seperti yang Anda lihat, Penutupan akan menerima dua parameter. Yang pertama adalah Item Keranjang untuk melakukan pemeriksaan terhadap. Parameter kedua adalah rowId dari CartItem ini. + +** Metode ini akan mengembalikan Koleksi yang berisi semua CartItems yang ditemukan ** + +Cara pencarian ini memberi Anda kontrol total atas proses pencarian dan memberi Anda kemampuan untuk membuat pencarian yang sangat tepat dan spesifik. + +### Cart :: setTax ($ rowId, $ taxRate) + +Anda dapat menggunakan metode `setTax ()` untuk mengubah tarif pajak yang berlaku untuk CartItem. Ini akan menimpa nilai yang ditetapkan dalam file konfigurasi. + +```php +Cart::setTax($rowId, 21); +$cart->setTax($rowId, 21); +``` + +### Cart::setGlobalTax($taxRate) + +Anda dapat menggunakan metode `setGlobalTax ()` untuk mengubah tarif pajak untuk semua item di troli. Item baru juga akan menerima setGlobalTax. + +```php +Cart::setGlobalTax(21); +$cart->setGlobalTax(21); +``` + +### Cart::setGlobalDiscount($discountRate) + +Anda dapat menggunakan metode `setGlobalDiscount ()` untuk mengubah tingkat diskonto untuk semua item di troli. Barang baru akan menerima diskon juga. + +```php +Cart::setGlobalDiscount(50); +$cart->setGlobalDiscount(50); +``` + +### Cart::setDiscount($rowId, $taxRate) + +Anda dapat menggunakan metode `setDiscount ()` untuk mengubah tingkat diskonto yang menerapkan CartItem. Perlu diingat bahwa nilai ini akan berubah jika Anda menetapkan diskon global untuk Keranjang sesudahnya. + +```php +Cart::setDiscount($rowId, 21); +$cart->setDiscount($rowId, 21); +``` + +### Buyable + +Untuk kenyamanan menambahkan item yang lebih cepat ke troli dan asosiasi otomatisnya, model Anda harus mengimplementasikan antarmuka `Dapat Dibeli` Anda dapat menggunakan sifat `CanBeBought` untuk mengimplementasikan metode yang diperlukan tetapi perlu diingat bahwa ini akan menggunakan bidang yang telah ditentukan pada model Anda untuk nilai yang diperlukan. + +```php +id; + } + public function getBuyableDescription(){ + return $this->name; + } + public function getBuyablePrice(){ + return $this->price; + } + public function getBuyableWeight(){ + return $this->weight; + } +``` + +Contoh: + +```php +id; + } + public function getBuyableDescription($options = null) { + return $this->name; + } + public function getBuyablePrice($options = null) { + return $this->price; + } +} +``` + +## Collections + +Dalam beberapa kasus, Keranjang akan mengembalikan kepada Anda Koleksi. Ini hanya Koleksi Laravel sederhana, sehingga semua metode yang dapat Anda panggil pada Koleksi Laravel juga tersedia pada hasilnya. + +Sebagai contoh, Anda dapat dengan cepat mendapatkan jumlah produk unik dalam keranjang: + +```php +Cart::content()->count(); +``` + +Atau Anda dapat mengelompokkan konten berdasarkan id produk: + +```php +Cart::content()->groupBy('id'); +``` + +## Instances + +Paket-paket mendukung beberapa instance dari kereta. Cara kerjanya seperti ini: + +Anda dapat mengatur instance keranjang saat ini dengan memanggil `Cart :: instance ('newInstance')`. Mulai saat ini, instance aktif dari cart adalah `newInstance`, jadi ketika Anda menambah, menghapus, atau mendapatkan konten dari cart, Anda bekerja dengan instance` newInstance` dari cart. +Jika Anda ingin mengganti instance, Anda cukup memanggil `Cart :: instance ('otherInstance')` lagi, dan Anda bekerja dengan `otherInstance` lagi. + +Contoh Kecil: + +```php +Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); + +// Get the content of the 'shopping' cart +Cart::content(); + +Cart::instance('wishlist')->add('sdjk922', 'Product 2', 1, 19.95, 550, ['size' => 'medium']); + +// Get the content of the 'wishlist' cart +Cart::content(); + +// If you want to get the content of the 'shopping' cart again +Cart::instance('shopping')->content(); + +// And the count of the 'wishlist' cart again +Cart::instance('wishlist')->count(); +``` + +Anda juga dapat menggunakan Kontrak `InstanceIdentifier` untuk memperpanjang Model yang diinginkan untuk menetapkan / membuat instance Cart untuknya. Ini juga memungkinkan untuk secara langsung mengatur diskon global. +``` +email; + } + + /** + * Get the unique identifier to load the Cart from + * + * @return int|string + */ + public function getInstanceGlobalDiscount($options = null) + { + return $this->discountRate ?: 0; + } +} + +// Inside Controller +$user = \Auth::user(); +$cart = Cart::instance($user); + + + +``` + +**N.B. Ingatlah bahwa troli tetap berada di set instance terakhir selama Anda tidak menyetel yang berbeda selama eksekusi skrip.** + +**N.B.2 Contoh cart default disebut `default`, jadi ketika Anda tidak menggunakan instance,` Cart :: konten (); `sama dengan` Cart :: instance ('default') -> konten () `.** + +## Models + +Karena sangat nyaman untuk dapat secara langsung mengakses model dari CartItem, apakah mungkin untuk mengaitkan model dengan barang-barang di dalam kereta. Katakanlah Anda memiliki model `Produk` di aplikasi Anda. Dengan metode `associate ()`, Anda dapat memberi tahu troli bahwa item di troli, terkait dengan model `Product`. + +Dengan begitu Anda dapat mengakses model Anda langsung dari `CartItem`! + +Model ini dapat diakses melalui properti `model` di CartItem. + +**Jika model Anda mengimplementasikan antarmuka `Buy Able` dan Anda menggunakan model Anda untuk menambahkan item ke troli, itu akan dikaitkan secara otomatis.** + +Berikut adalah contoh: + +```php + +// First we'll add the item to the cart. +$cartItem = Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); + +// Next we associate a model with the item. +Cart::associate($cartItem->rowId, 'Product'); + +// Or even easier, call the associate method on the CartItem! +$cartItem->associate('Product'); + +// You can even make it a one-liner +Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large'])->associate('Product'); + +// Now, when iterating over the content of the cart, you can access the model. +foreach(Cart::content() as $row) { + echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your cart.'; +} +``` +## Database + +- [Config](#configuration) +- [Storing the cart](#storing-the-cart) +- [Restoring the cart](#restoring-the-cart) + +### Konfigurasi +Untuk menyimpan keranjang ke dalam basis data sehingga Anda dapat mengambilnya nanti, paket perlu mengetahui koneksi basis data yang digunakan dan apa nama tabelnya. +Secara default paket akan menggunakan koneksi database default dan menggunakan tabel bernama `shoppingcart`. +Jika Anda ingin mengubah opsi ini, Anda harus menerbitkan file `config`. + + php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config" + +Ini akan memberi Anda file konfigurasi `cart.php` di mana Anda dapat melakukan perubahan. + +Untuk memudahkan hidup Anda, paket ini juga menyertakan `migration` yang siap digunakan yang dapat Anda terbitkan dengan menjalankan: + + php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations" + +Ini akan menempatkan file migrasi tabel `shoppingcart` ke direktori` database / migrations`. Sekarang yang harus Anda lakukan adalah menjalankan `php artisan migrate` untuk memigrasi basis data Anda. + +### Menyimpan ke Troli +Untuk menyimpan instance kereta ke dalam database, Anda harus memanggil metode `store ($ identifier)`. Di mana `$ identifier` adalah kunci acak, misalnya id atau nama pengguna pengguna. + + Cart::store('username'); + + // To store a cart instance named 'wishlist' + Cart::instance('wishlist')->store('username'); + +### Mengembalikan ke Troli +Jika Anda ingin mengambil keranjang dari database dan mengembalikannya, yang harus Anda lakukan adalah memanggil `restore ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. + + Cart::restore('username'); + + // To restore a cart instance named 'wishlist' + Cart::instance('wishlist')->restore('username'); + +### Menggabungkan Troli +Jika Anda ingin menggabungkan keranjang dengan keranjang lain dari basis data, yang harus Anda lakukan adalah memanggil `gabungan ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. Anda juga dapat menentukan apakah Anda ingin mempertahankan potongan harga dan tarif pajak item. + + // Merge the contents of 'savedcart' into 'username'. + Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); + +## Pengecualian + +Paket Cart akan mengeluarkan pengecualian jika terjadi kesalahan. Dengan cara ini lebih mudah untuk men-debug kode Anda menggunakan paket Cart atau untuk menangani kesalahan berdasarkan pada jenis pengecualian. Paket-paket Cart dapat membuang pengecualian berikut: + +| Exception | Reason | +| ---------------------------- | ---------------------------------------------------------------------------------- | +| *CartAlreadyStoredException* | Saat mencoba menyimpan keranjang yang sudah disimpan menggunakan pengenal yang ditentukan | +| *InvalidRowIDException* | Ketika rowId yang diteruskan tidak ada dalam instance troli saat ini | +| *UnknownModelException* | Saat Anda mencoba mengaitkan model yang tidak ada dengan Item Keranjang. | + +## Events + +Troli juga memiliki event. Ada lima event yang bisa Anda lakukan. + +| Event | Fired | Parameter | +| ------------- | ---------------------------------------- | -------------------------------- | +| cart.added | Saat item ditambahkan ke troli. | The `CartItem` that was added. | +| cart.updated | Ketika item dalam troli diperbarui. | The `CartItem` that was updated. | +| cart.removed | Ketika item dalam troli dihapus. | The `CartItem` that was removed. | +| cart.stored | Ketika isi trol disimpan. | - | +| cart.restored | Ketika konten keranjang Dikembalikan. | - | + +## Contoh + +Di bawah ini adalah sedikit contoh cara membuat daftar isi keranjang dalam sebuah tabel: + +```php + +// Tambahkan beberapa item di Kontroler Anda. +Cart::add('192ao12', 'Product 1', 1, 9.99); +Cart::add('1239ad0', 'Product 2', 2, 5.95, ['size' => 'large']); + +// Tampilkan konten dalam Tampilan. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ProductQtyPriceSubtotal
+

name; ?>

+

options->has('size') ? $row->options->size : ''); ?>

+
$price; ?>$total; ?>
 Subtotal
 Tax
 Total
+``` From 9cb198fb7f69781c0e2f61d7644e10c68df0f271 Mon Sep 17 00:00:00 2001 From: tiotobing <33707075+tiotobing@users.noreply.github.com> Date: Thu, 31 Oct 2019 11:10:39 +0700 Subject: [PATCH 26/52] Update README.md --- README.md | 233 +++++++++++++++++++++++++++--------------------------- 1 file changed, 116 insertions(+), 117 deletions(-) diff --git a/README.md b/README.md index 67a3fab..3481422 100644 --- a/README.md +++ b/README.md @@ -7,22 +7,22 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -Ini adalah percabangan dari [Crisane's LaravelShoppingcart] (https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 +This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. -## Instalasi +## Installation -Install paket(https://packagist.org/packages/bumbummen99/shoppingcart) menggunakan [Composer](http://getcomposer.org/). +Install the [package](https://packagist.org/packages/bumbummen99/shoppingcart) through [Composer](http://getcomposer.org/). -Jalankan Composer dengan menggunakan perintah berikut: +Run the Composer require command from the Terminal: composer require bumbummen99/shoppingcart -Sekarang Anda siap untuk mulai menggunakan shoppingcart di aplikasi Anda. +Now you're ready to start using the shoppingcart in your application. -**Pada versi 2 dari paket ini memungkinkan untuk menggunakan injeksi dependensi untuk memasukkan instance Class Cart ke controller Anda atau Class lain** +**As of version 2 of this package it's possibly to use dependency injection to inject an instance of the Cart class into your controller or other class** -## Gambaran -Lihat salah satu topik berikut untuk mempelajari lebih lanjut tentang LaravelShoppingcart +## Overview +Look at one of the following topics to learn more about LaravelShoppingcart * [Usage](#usage) * [Collections](#collections) @@ -33,51 +33,51 @@ Lihat salah satu topik berikut untuk mempelajari lebih lanjut tentang LaravelSho * [Events](#events) * [Example](#example) -## Penggunaan +## Usage -Shoppingcart memberi Anda metode berikut untuk digunakan: +The shoppingcart gives you the following methods to use: ### Cart::add() -Menambahkan item ke troli sangat sederhana, Anda cukup menggunakan metode `add ()`, yang menerima berbagai parameter. +Adding an item to the cart is really simple, you just use the `add()` method, which accepts a variety of parameters. -Dalam bentuknya yang paling mendasar, Anda dapat menentukan id, nama, jumlah, harga, dan berat produk yang ingin Anda tambahkan ke troli. +In its most basic form you can specify the id, name, quantity, price and weight of the product you'd like to add to the cart. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550); ``` -Sebagai opsional parameter kelima, Anda dapat memberikan opsi, sehingga Anda dapat menambahkan beberapa item dengan id yang sama, tetapi dengan (instance) ukuran yang berbeda. +As an optional fifth parameter you can pass it options, so you can add multiple items with the same id, but with (for instance) a different size. ```php Cart::add('293ad', 'Product 1', 1, 9.99, 550, ['size' => 'large']); ``` -**Metode `add ()` akan mengembalikan instance CartItem dari item yang baru saja Anda tambahkan ke troli.** +**The `add()` method will return an CartItem instance of the item you just added to the cart.** -Mungkin Anda lebih suka menambahkan item menggunakan array? Selama array berisi kunci yang diperlukan, Anda bisa meneruskannya ke metode. Tombol opsi adalah opsional. +Maybe you prefer to add the item using an array? As long as the array contains the required keys, you can pass it to the method. The options key is optional. ```php Cart::add(['id' => '293ad', 'name' => 'Product 1', 'qty' => 1, 'price' => 9.99, 'weight' => 550, 'options' => ['size' => 'large']]); ``` -Baru dalam versi 2 paket ini adalah kemungkinan untuk bekerja dengan antarmuka [Buyable] (#buyable). Cara kerjanya adalah bahwa Anda memiliki model yang mengimplementasikan antarmuka [Buyable] (#buyable), yang akan membuat Anda menerapkan beberapa metode sehingga paket tahu bagaimana cara mendapatkan id, nama, dan harga dari model Anda. -Dengan cara ini Anda bisa meneruskan metode `add ()` model dan kuantitas dan secara otomatis akan menambahkannya ke troli. +New in version 2 of the package is the possibility to work with the [Buyable](#buyable) interface. The way this works is that you have a model implement the [Buyable](#buyable) interface, which will make you implement a few methods so the package knows how to get the id, name and price from your model. +This way you can just pass the `add()` method a model and the quantity and it will automatically add it to the cart. -**Sebagai bonus tambahan, itu akan secara otomatis mengaitkan model dengan CartItem** +**As an added bonus it will automatically associate the model with the CartItem** ```php Cart::add($product, 1, ['size' => 'large']); ``` -Sebagai parameter ketiga opsional, Anda dapat menambahkan opsi. +As an optional third parameter you can add options. ```php Cart::add($product, 1, ['size' => 'large']); ``` -Terakhir, Anda juga dapat menambahkan banyak item ke troli sekaligus. -Anda bisa meneruskan metode `add ()` sebuah array array, atau array yang dapat dibeli dan mereka akan ditambahkan ke troli. +Finally, you can also add multipe items to the cart at once. +You can just pass the `add()` method an array of arrays, or an array of Buyables and they will be added to the cart. -**Saat menambahkan beberapa item ke troli, metode `add ()` akan mengembalikan array CartItems.** +**When adding multiple items to the cart, the `add()` method will return an array of CartItems.** ```php Cart::add([ @@ -91,17 +91,18 @@ Cart::add([$product1, $product2]); ### Cart::update() -Untuk memperbarui item di troli, Anda harus terlebih dahulu membutuhkan rowId item. -Selanjutnya Anda dapat menggunakan metode `update ()` untuk memperbaruinya. +To update an item in the cart, you'll first need the rowId of the item. +Next you can use the `update()` method to update it. -Jika Anda hanya ingin memperbarui kuantitas, Anda akan melewati metode pembaruan rowId dan kuantitas baru: +If you simply want to update the quantity, you'll pass the update method the rowId and the new quantity: ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; Cart::update($rowId, 2); // Will update the quantity ``` -Jika Anda ingin memperbarui lebih banyak atribut dari item, Anda dapat melewati metode pembaruan array atau `Dapat Dibeli` sebagai parameter kedua. Dengan cara ini Anda dapat memperbarui semua informasi item dengan rowId yang diberikan. + +If you want to update more attributes of the item, you can either pass the update method an array or a `Buyable` as the second parameter. This way you can update all information of the item with the given rowId. ```php Cart::update($rowId, ['name' => 'Product 1']); // Will update the name @@ -112,7 +113,7 @@ Cart::update($rowId, $product); // Will update the id, name and price ### Cart::remove() -Untuk menghapus item untuk keranjang, Anda akan membutuhkan rowId lagi. Baris ini. Apakah Anda hanya meneruskan ke metode `hapus ()` dan itu akan menghapus item dari keranjang. +To remove an item for the cart, you'll again need the rowId. This rowId you simply pass to the `remove()` method and it will remove the item from the cart. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -122,7 +123,7 @@ Cart::remove($rowId); ### Cart::get() -Jika Anda ingin mendapatkan item dari troli menggunakan rowId-nya, Anda bisa memanggil metode `get ()` di troli dan meneruskannya dengan rowId. +If you want to get an item from the cart using its rowId, you can simply call the `get()` method on the cart and pass it the rowId. ```php $rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; @@ -132,12 +133,13 @@ Cart::get($rowId); ### Cart::content() -Tentu saja Anda juga ingin mendapatkan konten gerobak. Di sinilah Anda akan menggunakan metode `konten`. Metode ini akan mengembalikan Koleksi CartItems yang dapat Anda ulangi dan tampilkan kontennya kepada pelanggan Anda. +Of course you also want to get the carts content. This is where you'll use the `content` method. This method will return a Collection of CartItems which you can iterate over and show the content to your customers. ```php Cart::content(); ``` -Metode ini akan mengembalikan konten instance keranjang saat ini, jika Anda ingin konten instance lain, cukup lakukan panggilan. + +This method will return the content of the current cart instance, if you want the content of another instance, simply chain the calls. ```php Cart::instance('wishlist')->content(); @@ -145,7 +147,7 @@ Cart::instance('wishlist')->content(); ### Cart::destroy() -Jika Anda ingin menghapus konten keranjang sepenuhnya, Anda dapat memanggil metode penghancuran di kereta. Ini akan menghapus semua CartItems dari troli untuk instance troli saat ini. +If you want to completely remove the content of a cart, you can call the destroy method on the cart. This will remove all CartItems from the cart for the current cart instance. ```php Cart::destroy(); @@ -153,117 +155,115 @@ Cart::destroy(); ### Cart::weight() -Metode `weight ()` dapat digunakan untuk mendapatkan total berat semua item di troli, mengingat berat dan kuantitasnya. - +The `weight()` method can be used to get the weight total of all items in the cart, given there weight and quantity. ```php Cart::weight(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::weight($decimals, $decimalSeperator, $thousandSeperator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> weight`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->weight`** ### Cart::total() -Maka `total ()` dapat digunakan untuk mendapatkan total yang dihitung dari semua item dalam troli, mengingat ada harga dan kuantitas. +The `total()` method can be used to get the calculated total of all items in the cart, given there price and quantity. ```php Cart::total(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::total($decimals, $decimalSeparator, $thousandSeparator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. - -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> total`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the total property `$cart->total`** ### Cart::tax() -Maka `tax ()` dapat digunakan untuk mendapatkan jumlah pajak yang dihitung untuk semua item di troli, mengingat ada harga dan kuantitas. +The `tax()` method can be used to get the calculated amount of tax for all items in the cart, given there price and quantity. ```php Cart::tax(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::tax($decimals, $decimalSeparator, $thousandSeparator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> tax`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the tax property `$cart->tax`** ### Cart::subtotal() -Maka `subtotal ()` dapat digunakan untuk mendapatkan total semua item dalam troli, dikurangi jumlah total pajak. +The `subtotal()` method can be used to get the total of all items in the cart, minus the total amount of tax. ```php Cart::subtotal(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::subtotal($decimals, $decimalSeparator, $thousandSeparator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> subtotal`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->subtotal`** ### Cart::discount() -Maka `diskon ()` dapat digunakan untuk mendapatkan diskon total semua item di troli. +The `discount()` method can be used to get the total discount of all items in the cart. ```php Cart::discount(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::discount($decimals, $decimalSeparator, $thousandSeparator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> discount`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->discount`** ### Cart::initial() -maka `initial ()` dapat digunakan untuk mendapatkan harga total semua item di troli sebelum diskon. +The `initial()` method can be used to get the total price of all items in the cart before discount. ```php Cart::initial(); ``` -Metode ini akan memformat hasilnya secara otomatis, yang dapat Anda atur menggunakan tiga parameter opsional +The method will automatically format the result, which you can tweak using the three optional parameters ```php Cart::initial($decimals, $decimalSeparator, $thousandSeparator); ``` -Anda dapat mengatur format angka default dalam file konfigurasi. +You can set the default number format in the config file. -**Jika Anda tidak menggunakan Facade, tetapi menggunakan injeksi ketergantungan pada Pengontrol Anda (misalnya), Anda juga bisa mendapatkan total properti `$ cart-> initial`** +**If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->initial`** ### Cart::count() -Jika Anda ingin tahu berapa banyak item yang ada di troli Anda, Anda dapat menggunakan metode `count ()`. Metode ini akan mengembalikan jumlah total barang dalam kereta. Jadi, jika Anda telah menambahkan 2 buku dan 1 kemeja, itu akan mengembalikan 3 item. +If you want to know how many items there are in your cart, you can use the `count()` method. This method will return the total number of items in the cart. So if you've added 2 books and 1 shirt, it will return 3 items. ```php Cart::count(); @@ -272,13 +272,13 @@ $cart->count(); ### Cart::search() -Untuk menemukan item di troli, Anda dapat menggunakan metode `search ()`. +To find an item in the cart, you can use the `search()` method. -**Metode ini diubah pada versi 2** +**This method was changed on version 2** -Di belakang layar, metode ini hanya menggunakan metode filter dari kelas Laravel Collection. Ini berarti Anda harus memberikannya suatu Penutupan di mana Anda akan menentukan istilah pencarian Anda. +Behind the scenes, the method simply uses the filter method of the Laravel Collection class. This means you must pass it a Closure in which you'll specify you search terms. -Jika Anda misalnya ingin menemukan semua item dengan id 1: +If you for instance want to find all items with an id of 1: ```php $cart->search(function ($cartItem, $rowId) { @@ -286,15 +286,15 @@ $cart->search(function ($cartItem, $rowId) { }); ``` -Seperti yang Anda lihat, Penutupan akan menerima dua parameter. Yang pertama adalah Item Keranjang untuk melakukan pemeriksaan terhadap. Parameter kedua adalah rowId dari CartItem ini. +As you can see the Closure will receive two parameters. The first is the CartItem to perform the check against. The second parameter is the rowId of this CartItem. -** Metode ini akan mengembalikan Koleksi yang berisi semua CartItems yang ditemukan ** +**The method will return a Collection containing all CartItems that where found** -Cara pencarian ini memberi Anda kontrol total atas proses pencarian dan memberi Anda kemampuan untuk membuat pencarian yang sangat tepat dan spesifik. +This way of searching gives you total control over the search process and gives you the ability to create very precise and specific searches. -### Cart :: setTax ($ rowId, $ taxRate) +### Cart::setTax($rowId, $taxRate) -Anda dapat menggunakan metode `setTax ()` untuk mengubah tarif pajak yang berlaku untuk CartItem. Ini akan menimpa nilai yang ditetapkan dalam file konfigurasi. +You can use the `setTax()` method to change the tax rate that applies to the CartItem. This will overwrite the value set in the config file. ```php Cart::setTax($rowId, 21); @@ -303,7 +303,7 @@ $cart->setTax($rowId, 21); ### Cart::setGlobalTax($taxRate) -Anda dapat menggunakan metode `setGlobalTax ()` untuk mengubah tarif pajak untuk semua item di troli. Item baru juga akan menerima setGlobalTax. +You can use the `setGlobalTax()` method to change the tax rate for all items in the cart. New items will receive the setGlobalTax as well. ```php Cart::setGlobalTax(21); @@ -312,7 +312,7 @@ $cart->setGlobalTax(21); ### Cart::setGlobalDiscount($discountRate) -Anda dapat menggunakan metode `setGlobalDiscount ()` untuk mengubah tingkat diskonto untuk semua item di troli. Barang baru akan menerima diskon juga. +You can use the `setGlobalDiscount()` method to change the discount rate for all items in the cart. New items will receive the discount as well. ```php Cart::setGlobalDiscount(50); @@ -321,7 +321,7 @@ $cart->setGlobalDiscount(50); ### Cart::setDiscount($rowId, $taxRate) -Anda dapat menggunakan metode `setDiscount ()` untuk mengubah tingkat diskonto yang menerapkan CartItem. Perlu diingat bahwa nilai ini akan berubah jika Anda menetapkan diskon global untuk Keranjang sesudahnya. +You can use the `setDiscount()` method to change the discount rate that applies a CartItem. Keep in mind that this value will be changed if you set the global discount for the Cart afterwards. ```php Cart::setDiscount($rowId, 21); @@ -330,8 +330,7 @@ $cart->setDiscount($rowId, 21); ### Buyable -Untuk kenyamanan menambahkan item yang lebih cepat ke troli dan asosiasi otomatisnya, model Anda harus mengimplementasikan antarmuka `Dapat Dibeli` Anda dapat menggunakan sifat `CanBeBought` untuk mengimplementasikan metode yang diperlukan tetapi perlu diingat bahwa ini akan menggunakan bidang yang telah ditentukan pada model Anda untuk nilai yang diperlukan. - +For the convenience of faster adding items to cart and their automatic association, your model has to implement the `Buyable` interface. You can use the `CanBeBought` trait to implement the required methods but keep in mind that these will use predefined fields on your model for the required values. ```php count(); ``` -Atau Anda dapat mengelompokkan konten berdasarkan id produk: +Or you can group the content by the id of the products: ```php Cart::content()->groupBy('id'); @@ -401,12 +400,12 @@ Cart::content()->groupBy('id'); ## Instances -Paket-paket mendukung beberapa instance dari kereta. Cara kerjanya seperti ini: +The packages supports multiple instances of the cart. The way this works is like this: -Anda dapat mengatur instance keranjang saat ini dengan memanggil `Cart :: instance ('newInstance')`. Mulai saat ini, instance aktif dari cart adalah `newInstance`, jadi ketika Anda menambah, menghapus, atau mendapatkan konten dari cart, Anda bekerja dengan instance` newInstance` dari cart. -Jika Anda ingin mengganti instance, Anda cukup memanggil `Cart :: instance ('otherInstance')` lagi, dan Anda bekerja dengan `otherInstance` lagi. +You can set the current instance of the cart by calling `Cart::instance('newInstance')`. From this moment, the active instance of the cart will be `newInstance`, so when you add, remove or get the content of the cart, you're work with the `newInstance` instance of the cart. +If you want to switch instances, you just call `Cart::instance('otherInstance')` again, and you're working with the `otherInstance` again. -Contoh Kecil: +So a little example: ```php Cart::instance('shopping')->add('192ao12', 'Product 1', 1, 9.99, 550); @@ -426,7 +425,7 @@ Cart::instance('shopping')->content(); Cart::instance('wishlist')->count(); ``` -Anda juga dapat menggunakan Kontrak `InstanceIdentifier` untuk memperpanjang Model yang diinginkan untuk menetapkan / membuat instance Cart untuknya. Ini juga memungkinkan untuk secara langsung mengatur diskon global. +You can also use the `InstanceIdentifier` Contract to extend a desired Model to assign / create a Cart instance for it. This also allows to directly set the global discount. ``` konten () `.** +**N.B.2 The default cart instance is called `default`, so when you're not using instances,`Cart::content();` is the same as `Cart::instance('default')->content()`.** ## Models -Karena sangat nyaman untuk dapat secara langsung mengakses model dari CartItem, apakah mungkin untuk mengaitkan model dengan barang-barang di dalam kereta. Katakanlah Anda memiliki model `Produk` di aplikasi Anda. Dengan metode `associate ()`, Anda dapat memberi tahu troli bahwa item di troli, terkait dengan model `Product`. +Because it can be very convenient to be able to directly access a model from a CartItem is it possible to associate a model with the items in the cart. Let's say you have a `Product` model in your application. With the `associate()` method, you can tell the cart that an item in the cart, is associated to the `Product` model. -Dengan begitu Anda dapat mengakses model Anda langsung dari `CartItem`! +That way you can access your model right from the `CartItem`! -Model ini dapat diakses melalui properti `model` di CartItem. +The model can be accessed via the `model` property on the CartItem. -**Jika model Anda mengimplementasikan antarmuka `Buy Able` dan Anda menggunakan model Anda untuk menambahkan item ke troli, itu akan dikaitkan secara otomatis.** +**If your model implements the `Buyable` interface and you used your model to add the item to the cart, it will associate automatically.** -Berikut adalah contoh: +Here is an example: ```php @@ -509,76 +508,76 @@ foreach(Cart::content() as $row) { - [Storing the cart](#storing-the-cart) - [Restoring the cart](#restoring-the-cart) -### Konfigurasi -Untuk menyimpan keranjang ke dalam basis data sehingga Anda dapat mengambilnya nanti, paket perlu mengetahui koneksi basis data yang digunakan dan apa nama tabelnya. -Secara default paket akan menggunakan koneksi database default dan menggunakan tabel bernama `shoppingcart`. -Jika Anda ingin mengubah opsi ini, Anda harus menerbitkan file `config`. +### Configuration +To save cart into the database so you can retrieve it later, the package needs to know which database connection to use and what the name of the table is. +By default the package will use the default database connection and use a table named `shoppingcart`. +If you want to change these options, you'll have to publish the `config` file. php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="config" -Ini akan memberi Anda file konfigurasi `cart.php` di mana Anda dapat melakukan perubahan. +This will give you a `cart.php` config file in which you can make the changes. -Untuk memudahkan hidup Anda, paket ini juga menyertakan `migration` yang siap digunakan yang dapat Anda terbitkan dengan menjalankan: +To make your life easy, the package also includes a ready to use `migration` which you can publish by running: php artisan vendor:publish --provider="Gloudemans\Shoppingcart\ShoppingcartServiceProvider" --tag="migrations" -Ini akan menempatkan file migrasi tabel `shoppingcart` ke direktori` database / migrations`. Sekarang yang harus Anda lakukan adalah menjalankan `php artisan migrate` untuk memigrasi basis data Anda. +This will place a `shoppingcart` table's migration file into `database/migrations` directory. Now all you have to do is run `php artisan migrate` to migrate your database. -### Menyimpan ke Troli -Untuk menyimpan instance kereta ke dalam database, Anda harus memanggil metode `store ($ identifier)`. Di mana `$ identifier` adalah kunci acak, misalnya id atau nama pengguna pengguna. +### Storing the cart +To store your cart instance into the database, you have to call the `store($identifier) ` method. Where `$identifier` is a random key, for instance the id or username of the user. Cart::store('username'); // To store a cart instance named 'wishlist' Cart::instance('wishlist')->store('username'); -### Mengembalikan ke Troli -Jika Anda ingin mengambil keranjang dari database dan mengembalikannya, yang harus Anda lakukan adalah memanggil `restore ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. +### Restoring the cart +If you want to retrieve the cart from the database and restore it, all you have to do is call the `restore($identifier)` where `$identifier` is the key you specified for the `store` method. Cart::restore('username'); // To restore a cart instance named 'wishlist' Cart::instance('wishlist')->restore('username'); -### Menggabungkan Troli -Jika Anda ingin menggabungkan keranjang dengan keranjang lain dari basis data, yang harus Anda lakukan adalah memanggil `gabungan ($ identifier)` di mana `$ identifier` adalah kunci yang Anda tentukan untuk metode` store`. Anda juga dapat menentukan apakah Anda ingin mempertahankan potongan harga dan tarif pajak item. +### Merge the cart +If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items. // Merge the contents of 'savedcart' into 'username'. Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); -## Pengecualian +## Exceptions -Paket Cart akan mengeluarkan pengecualian jika terjadi kesalahan. Dengan cara ini lebih mudah untuk men-debug kode Anda menggunakan paket Cart atau untuk menangani kesalahan berdasarkan pada jenis pengecualian. Paket-paket Cart dapat membuang pengecualian berikut: +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: | Exception | Reason | | ---------------------------- | ---------------------------------------------------------------------------------- | -| *CartAlreadyStoredException* | Saat mencoba menyimpan keranjang yang sudah disimpan menggunakan pengenal yang ditentukan | -| *InvalidRowIDException* | Ketika rowId yang diteruskan tidak ada dalam instance troli saat ini | -| *UnknownModelException* | Saat Anda mencoba mengaitkan model yang tidak ada dengan Item Keranjang. | +| *CartAlreadyStoredException* | When trying to store a cart that was already stored using the specified identifier | +| *InvalidRowIDException* | When the rowId that got passed doesn't exists in the current cart instance | +| *UnknownModelException* | When you try to associate an none existing model to a CartItem. | ## Events -Troli juga memiliki event. Ada lima event yang bisa Anda lakukan. +The cart also has events build in. There are five events available for you to listen for. | Event | Fired | Parameter | | ------------- | ---------------------------------------- | -------------------------------- | -| cart.added | Saat item ditambahkan ke troli. | The `CartItem` that was added. | -| cart.updated | Ketika item dalam troli diperbarui. | The `CartItem` that was updated. | -| cart.removed | Ketika item dalam troli dihapus. | The `CartItem` that was removed. | -| cart.stored | Ketika isi trol disimpan. | - | -| cart.restored | Ketika konten keranjang Dikembalikan. | - | +| cart.added | When an item was added to the cart. | The `CartItem` that was added. | +| cart.updated | When an item in the cart was updated. | The `CartItem` that was updated. | +| 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. | - | -## Contoh +## Example -Di bawah ini adalah sedikit contoh cara membuat daftar isi keranjang dalam sebuah tabel: +Below is a little example of how to list the cart content in a table: ```php -// Tambahkan beberapa item di Kontroler Anda. +// Add some items in your Controller. Cart::add('192ao12', 'Product 1', 1, 9.99); Cart::add('1239ad0', 'Product 2', 2, 5.95, ['size' => 'large']); -// Tampilkan konten dalam Tampilan. +// Display the content in a View. From bb59a2e2dd836358f37d951cce9600dbf6885be8 Mon Sep 17 00:00:00 2001 From: Cristian Date: Thu, 31 Oct 2019 13:14:22 +0100 Subject: [PATCH 27/52] Added a method to erase stored cart --- README.md | 9 +++++++++ src/Cart.php | 23 +++++++++++++++++++++++ tests/CartTest.php | 22 ++++++++++++++++++++++ 3 files changed, 54 insertions(+) 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. * From cb470f69a387feb5d3eb642ca41c348273d9c43b Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Thu, 31 Oct 2019 21:04:34 +0100 Subject: [PATCH 28/52] Fix products sequence after changing cart item options --- src/Cart.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Cart.php b/src/Cart.php index 97097a0..17cbb3a 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -180,6 +180,8 @@ class Cart $content = $this->getContent(); if ($rowId !== $cartItem->rowId) { + $itemOldIndex = $content->keys()->search($rowId); + $content->pull($rowId); if ($content->has($cartItem->rowId)) { @@ -193,7 +195,14 @@ class Cart return; } else { - $content->put($cartItem->rowId, $cartItem); + if (isset($itemOldIndex)) + { + $content = $content->slice(0, $itemOldIndex) + ->merge([$cartItem->rowId => $cartItem]) + ->merge($content->slice($itemOldIndex)); + } else { + $content->put($cartItem->rowId, $cartItem); + } } $this->events->dispatch('cart.updated', $cartItem); From 5d7aee42d7e2fd4b00f46b69e62c81ed3d9f48b4 Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Thu, 31 Oct 2019 21:33:05 +0100 Subject: [PATCH 29/52] Fix code style --- src/Cart.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 17cbb3a..7f2445d 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -195,8 +195,7 @@ class Cart return; } else { - if (isset($itemOldIndex)) - { + if (isset($itemOldIndex)) { $content = $content->slice(0, $itemOldIndex) ->merge([$cartItem->rowId => $cartItem]) ->merge($content->slice($itemOldIndex)); From e4e9a6ec6ebbcad8a4682dff7f957aca3532d2ec Mon Sep 17 00:00:00 2001 From: Andrew Savchenko Date: Sat, 2 Nov 2019 14:29:54 +0100 Subject: [PATCH 30/52] Add a test case to assert items sequence is kept if the options changed --- tests/CartTest.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/CartTest.php b/tests/CartTest.php index e9acea9..5c7d8e5 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -399,6 +399,21 @@ class CartTest extends TestCase $this->assertRowsInCart(1, $cart); } + /** @test */ + public function it_will_keep_items_sequence_if_the_options_changed() + { + $cart = $this->getCart(); + + $cart->add(new BuyableProduct(), 1, ['color' => 'red']); + $cart->add(new BuyableProduct(), 1, ['color' => 'green']); + $cart->add(new BuyableProduct(), 1, ['color' => 'blue']); + + $cart->update($cart->content()->values()[1]->rowId, ['options' => ['color' => 'yellow']]); + + $this->assertRowsInCart(3, $cart); + $this->assertEquals('yellow', $cart->content()->values()[1]->options->color); + } + /** @test */ public function it_can_remove_an_item_from_the_cart() { From 07a776aa333c3bd9528f9e077916abfde3e13422 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sat, 16 Nov 2019 23:43:18 +0100 Subject: [PATCH 31/52] StyleCI --- src/Cart.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Cart.php b/src/Cart.php index 4a0d28c..8c2023e 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -650,7 +650,7 @@ class Cart $this->events->dispatch('cart.erased'); } - + /** * Merges the contents of another cart into this cart. * From 73173955adfa1a4f76c7d6a6e6cc025aabc6daba Mon Sep 17 00:00:00 2001 From: Patrick Date: Sat, 16 Nov 2019 23:57:31 +0100 Subject: [PATCH 32/52] Update Cart.php --- src/Cart.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 8c2023e..61491fd 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -645,8 +645,7 @@ class Cart return; } - $this->getConnection()->table($this->getTableName()) - ->where('identifier', $identifier)->delete(); + $this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->delete(); $this->events->dispatch('cart.erased'); } From 1341863d65f476f4fd03f77fe88ad6781baf7e7a Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Mon, 18 Nov 2019 03:14:53 +0100 Subject: [PATCH 33/52] Dispatch "cart.merged" event,added a parameter to avoid dispatching "cart.added" events while merging --- README.md | 5 ++-- src/Cart.php | 25 ++++++++++++-------- tests/CartTest.php | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 3481422..643b5b0 100644 --- a/README.md +++ b/README.md @@ -540,10 +540,10 @@ If you want to retrieve the cart from the database and restore it, all you have Cart::instance('wishlist')->restore('username'); ### Merge the cart -If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items. +If you want to merge the cart with another one from the database, all you have to do is call the `merge($identifier)` where `$identifier` is the key you specified for the `store` method. You can also define if you want to keep the discount and tax rates of the items and if you want to dispatch "cart.added" events. // Merge the contents of 'savedcart' into 'username'. - Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate); + Cart::instance('username')->merge('savedcart', $keepDiscount, $keepTaxrate, $dispatchAdd); ## Exceptions @@ -564,6 +564,7 @@ The cart also has events build in. There are five events available for you to li | cart.added | When an item was added to the cart. | The `CartItem` that was added. | | cart.updated | When an item in the cart was updated. | The `CartItem` that was updated. | | cart.removed | When an item is removed from the cart. | The `CartItem` that was removed. | +| cart.merged | When the content of a cart is merged | - | | cart.stored | When the content of a cart was stored. | - | | cart.restored | When the content of a cart was restored. | - | diff --git a/src/Cart.php b/src/Cart.php index 7f2445d..5ace253 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -46,7 +46,7 @@ class Cart private $discount = 0; /** - * Defines the discount percentage. + * Defines the tax rate * * @var float */ @@ -126,13 +126,14 @@ class Cart /** * Add an item to the cart. * - * @param \Gloudemans\Shoppingcart\CartItem $item Item to add to the Cart - * @param bool $keepDiscount Keep the discount rate of the Item - * @param bool $keepTax Keep the Tax rate of the Item + * @param \Gloudemans\Shoppingcart\CartItem $item Item to add to the Cart + * @param bool $keepDiscount Keep the discount rate of the Item + * @param bool $keepTax Keep the Tax rate of the Item + * @param bool $dispatchEvent * * @return \Gloudemans\Shoppingcart\CartItem The CartItem */ - public function addCartItem($item, $keepDiscount = false, $keepTax = false) + public function addCartItem($item, $keepDiscount = false, $keepTax = false, $dispatchEvent = true) { if (!$keepDiscount) { $item->setDiscountRate($this->discount); @@ -150,7 +151,9 @@ class Cart $content->put($item->rowId, $item); - $this->events->dispatch('cart.added', $item); + if ($dispatchEvent) { + $this->events->dispatch('cart.added', $item); + } $this->session->put($this->instance, $content); @@ -632,8 +635,7 @@ class Cart $this->instance($currentInstance); - $this->getConnection()->table($this->getTableName()) - ->where('identifier', $identifier)->delete(); + $this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->delete(); } /** @@ -642,10 +644,11 @@ class Cart * @param mixed $identifier Identifier of the Cart to merge with. * @param bool $keepDiscount Keep the discount of the CartItems. * @param bool $keepTax Keep the tax of the CartItems. + * @param bool $dispatchAdd Flag to dispatch the add events. * * @return bool */ - public function merge($identifier, $keepDiscount = false, $keepTax = false) + public function merge($identifier, $keepDiscount = false, $keepTax = false, $dispatchAdd = true) { if (!$this->storedCartWithIdentifierExists($identifier)) { return false; @@ -657,9 +660,11 @@ class Cart $storedContent = unserialize($stored->content); foreach ($storedContent as $cartItem) { - $this->addCartItem($cartItem, $keepDiscount, $keepTax); + $this->addCartItem($cartItem, $keepDiscount, $keepTax, $dispatchAdd); } + $this->events->dispatch('cart.merged'); + return true; } diff --git a/tests/CartTest.php b/tests/CartTest.php index 5c7d8e5..0edf156 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1204,6 +1204,65 @@ class CartTest extends TestCase $this->assertEquals('large', $cartItem->options->size); } + /** @test */ + public function it_can_merge_without_dispatching_add_events() + { + $this->artisan('migrate', [ + '--database' => 'testing', + ]); + + $cart = $this->getCartDiscount(50); + $cart->add(new BuyableProduct(1, 'Item', 10.00), 1); + $cart->add(new BuyableProduct(2, 'Item 2', 10.00), 1); + $cart->store('test'); + + Event::fakeFor(function () { + $cart2 = $this->getCart(); + $cart2->instance('test2'); + $cart2->setGlobalTax(0); + $cart2->setGlobalDiscount(0); + + $this->assertEquals('0', $cart2->countInstances()); + + $cart2->merge('test',null,null,false); + + Event::assertNotDispatched('cart.added'); + Event::assertDispatched('cart.merged'); + + $this->assertEquals('2', $cart2->countInstances()); + $this->assertEquals(20, $cart2->totalFloat()); + }); + } + + /** @test */ + public function it_can_merge_dispatching_add_events() + { + $this->artisan('migrate', [ + '--database' => 'testing', + ]); + + $cart = $this->getCartDiscount(50); + $cart->add(new BuyableProduct(1, 'Item', 10.00), 1); + $cart->add(new BuyableProduct(2, 'Item 2', 10.00), 1); + $cart->store('test'); + + Event::fakeFor(function () { + $cart2 = $this->getCart(); + $cart2->instance('test2'); + $cart2->setGlobalTax(0); + $cart2->setGlobalDiscount(0); + + $this->assertEquals('0', $cart2->countInstances()); + + $cart2->merge('test'); + + Event::assertDispatched('cart.added',2); + Event::assertDispatched('cart.merged'); + $this->assertEquals('2', $cart2->countInstances()); + $this->assertEquals(20, $cart2->totalFloat()); + }); + } + /** * Get an instance of the cart. * From 8383901fba788a7ac761873fbd414963d910708d Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 19 Nov 2019 01:36:09 +0100 Subject: [PATCH 34/52] Update Cart.php --- src/Cart.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 5ace253..fe1571b 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -46,7 +46,7 @@ class Cart private $discount = 0; /** - * Defines the tax rate + * Defines the tax rate. * * @var float */ @@ -126,10 +126,10 @@ class Cart /** * Add an item to the cart. * - * @param \Gloudemans\Shoppingcart\CartItem $item Item to add to the Cart - * @param bool $keepDiscount Keep the discount rate of the Item - * @param bool $keepTax Keep the Tax rate of the Item - * @param bool $dispatchEvent + * @param \Gloudemans\Shoppingcart\CartItem $item Item to add to the Cart + * @param bool $keepDiscount Keep the discount rate of the Item + * @param bool $keepTax Keep the Tax rate of the Item + * @param bool $dispatchEvent * * @return \Gloudemans\Shoppingcart\CartItem The CartItem */ From b8005be37a51dddfadae38a6c2b349c1ba376cfd Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 19 Nov 2019 01:40:05 +0100 Subject: [PATCH 35/52] Update CartTest.php --- tests/CartTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/CartTest.php b/tests/CartTest.php index 0edf156..5b28cae 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1224,7 +1224,7 @@ class CartTest extends TestCase $this->assertEquals('0', $cart2->countInstances()); - $cart2->merge('test',null,null,false); + $cart2->merge('test', null, null, false); Event::assertNotDispatched('cart.added'); Event::assertDispatched('cart.merged'); @@ -1256,7 +1256,7 @@ class CartTest extends TestCase $cart2->merge('test'); - Event::assertDispatched('cart.added',2); + Event::assertDispatched('cart.added', 2); Event::assertDispatched('cart.merged'); $this->assertEquals('2', $cart2->countInstances()); $this->assertEquals(20, $cart2->totalFloat()); From 677bc1c2772d3743360bd4c618a16784510796d7 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sat, 21 Dec 2019 17:22:58 +0100 Subject: [PATCH 36/52] Fix link --- README_Idn.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_Idn.md b/README_Idn.md index 67a3fab..54b7b37 100644 --- a/README_Idn.md +++ b/README_Idn.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -Ini adalah percabangan dari [Crisane's LaravelShoppingcart] (https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 +Ini adalah percabangan dari [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 ## Instalasi From de1bf2a5eacb308d8e3cd412ce9440a08dd68f2c Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Thu, 9 Jan 2020 19:15:48 +0100 Subject: [PATCH 37/52] fix issue with the priceTax value that is not dynamically retrieved --- src/CartItem.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/CartItem.php b/src/CartItem.php index 5efb546..6ba3f5f 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -279,7 +279,6 @@ class CartItem implements Arrayable, Jsonable $this->id = $item->getBuyableIdentifier($this->options); $this->name = $item->getBuyableDescription($this->options); $this->price = $item->getBuyablePrice($this->options); - $this->priceTax = $this->price + $this->tax; } /** @@ -296,7 +295,6 @@ class CartItem implements Arrayable, Jsonable $this->name = Arr::get($attributes, 'name', $this->name); $this->price = Arr::get($attributes, 'price', $this->price); $this->weight = Arr::get($attributes, 'weight', $this->weight); - $this->priceTax = $this->price + $this->tax; $this->options = new CartItemOptions(Arr::get($attributes, 'options', $this->options)); $this->rowId = $this->generateRowId($this->id, $this->options->all()); From 1ffd1a5dfa8302cfb6cd55040b019d0e0b9adc4f Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Fri, 10 Jan 2020 01:54:45 +0100 Subject: [PATCH 38/52] test added --- tests/CartTest.php | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/CartTest.php b/tests/CartTest.php index 5b28cae..e48d5b6 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -959,6 +959,52 @@ class CartTest extends TestCase $this->assertEquals(11.90, $cartItem->total(2)); } + /** @test */ + public function it_can_calculate_all_values_after_updating_from_array() + { + $cart = $this->getCartDiscount(50); + $cart->add(new BuyableProduct(1, 'First item', 10.00), 1); + + $cart->update('027c91341fd5cf4d2579b49c4b6a90da', ['qty'=>2]); + + $cartItem = $cart->get('027c91341fd5cf4d2579b49c4b6a90da'); + + $cart->setTax('027c91341fd5cf4d2579b49c4b6a90da', 19); + + $this->assertEquals(10.00, $cartItem->price(2)); + $this->assertEquals(5.00, $cartItem->discount(2)); + $this->assertEquals(10.00, $cartItem->discountTotal(2)); + $this->assertEquals(5.00, $cartItem->priceTarget(2)); + $this->assertEquals(10.00, $cartItem->subtotal(2)); + $this->assertEquals(0.95, $cartItem->tax(2)); + $this->assertEquals(1.90, $cartItem->taxTotal(2)); + $this->assertEquals(5.95, $cartItem->priceTax(2)); + $this->assertEquals(11.90, $cartItem->total(2)); + } + + /** @test */ + public function it_can_calculate_all_values_after_updating_from_buyable() + { + $cart = $this->getCartDiscount(50); + $cart->add(new BuyableProduct(1, 'First item', 5.00), 2); + + $cart->update('027c91341fd5cf4d2579b49c4b6a90da', new BuyableProduct(1, 'First item', 10.00)); + + $cartItem = $cart->get('027c91341fd5cf4d2579b49c4b6a90da'); + + $cart->setTax('027c91341fd5cf4d2579b49c4b6a90da', 19); + + $this->assertEquals(10.00, $cartItem->price(2)); + $this->assertEquals(5.00, $cartItem->discount(2)); + $this->assertEquals(10.00, $cartItem->discountTotal(2)); + $this->assertEquals(5.00, $cartItem->priceTarget(2)); + $this->assertEquals(10.00, $cartItem->subtotal(2)); + $this->assertEquals(0.95, $cartItem->tax(2)); + $this->assertEquals(1.90, $cartItem->taxTotal(2)); + $this->assertEquals(5.95, $cartItem->priceTax(2)); + $this->assertEquals(11.90, $cartItem->total(2)); + } + /** @test */ public function it_will_destroy_the_cart_when_the_user_logs_out_and_the_config_setting_was_set_to_true() { From 9dc16ae784fab47a2bb5a116072e5ff9898588d7 Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 14 Jan 2020 21:20:38 +0100 Subject: [PATCH 39/52] Correct original auther name --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 952b9af..612f27a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. +This is a fork of [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. ## Installation From 14f8baa50a1b7b322700910e50f0d2c09afadfa6 Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 14 Jan 2020 21:21:05 +0100 Subject: [PATCH 40/52] Correct original authors name --- README_Idn.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_Idn.md b/README_Idn.md index 54b7b37..3839008 100644 --- a/README_Idn.md +++ b/README_Idn.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -Ini adalah percabangan dari [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 +Ini adalah percabangan dari [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) dikembangkan dengan fitur-fitur minor yang kompatibel dengan Laravel 6 ## Instalasi From df121b20d3b50c3d9a01109792ba2e964a1e3db2 Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 14 Jan 2020 21:21:33 +0100 Subject: [PATCH 41/52] Correct original authors name --- README_uk-UA.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README_uk-UA.md b/README_uk-UA.md index 4c835f1..af44477 100644 --- a/README_uk-UA.md +++ b/README_uk-UA.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -Цей репозиторій є відгалуженням [Crisane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) та містить додаткові незначні доповнення, сумісні з Laravel 6. +Цей репозиторій є відгалуженням [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) та містить додаткові незначні доповнення, сумісні з Laravel 6. ## Встановлення From 9cdacf901ccd43ce0c1ed51c8e7a0bbab49e7933 Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Tue, 14 Jan 2020 22:33:12 +0100 Subject: [PATCH 42/52] changed the strategy for cart values calculation (taxes per row), test, some fixes --- src/Cart.php | 10 +++++----- src/CartItem.php | 41 +++++++++++++++++++++++++++++------------ tests/CartTest.php | 27 ++++++++++++++++++++++++--- 3 files changed, 58 insertions(+), 20 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 0ead1f5..7a0333e 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -375,7 +375,7 @@ class Cart } /** - * Get the subtotal (total - tax) of the items in the cart. + * Get the discount of the items in the cart. * * @return float */ @@ -387,7 +387,7 @@ class Cart } /** - * Get the subtotal (total - tax) of the items in the cart as formatted string. + * Get the discount of the items in the cart as formatted string. * * @param int $decimals * @param string $decimalPoint @@ -401,11 +401,11 @@ class Cart } /** - * Get the subtotal (total - tax) of the items in the cart. + * Get the price of the items in the cart. * * @return float */ - public function initialFloat() + public function initialFloat() // TODO: rename and use priceTotal { return $this->getContent()->reduce(function ($initial, CartItem $cartItem) { return $initial + ($cartItem->qty * $cartItem->price); @@ -413,7 +413,7 @@ class Cart } /** - * Get the subtotal (total - tax) of the items in the cart as formatted string. + * Get the price of the items in the cart as formatted string. * * @param int $decimals * @param string $decimalPoint diff --git a/src/CartItem.php b/src/CartItem.php index 6ba3f5f..a7387cc 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -253,6 +253,20 @@ class CartItem implements Arrayable, Jsonable return $this->numberFormat($this->discountTotal, $decimals, $decimalPoint, $thousandSeperator); } + /** + * Returns the formatted total price for this cart item. + * + * @param int $decimals + * @param string $decimalPoint + * @param string $thousandSeperator + * + * @return string + */ + public function priceTotal($decimals = null, $decimalPoint = null, $thousandSeperator = null) + { + return $this->numberFormat($this->priceTotal, $decimals, $decimalPoint, $thousandSeperator); + } + /** * Set the quantity for this cart item. * @@ -354,26 +368,29 @@ class CartItem implements Arrayable, Jsonable if (property_exists($this, $attribute)) { return $this->{$attribute}; } + $decimals = config('cart.format.decimals', 2); switch ($attribute) { case 'discount': return $this->price * ($this->discountRate / 100); - case 'priceTarget': - return $this->price - $this->discount; - case 'subtotal': - return $this->priceTarget * $this->qty; case 'tax': - return $this->priceTarget * ($this->taxRate / 100); + return round($this->priceTarget * ($this->taxRate / 100), $decimals); case 'priceTax': - return $this->priceTarget + $this->tax; - case 'total': - return $this->priceTax * $this->qty; - case 'taxTotal': - return $this->tax * $this->qty; + return round($this->priceTarget + $this->tax, $decimals); case 'discountTotal': - return $this->discount * $this->qty; + return round ($this->discount * $this->qty, $decimals); case 'weightTotal': - return $this->weight * $this->qty; + return round($this->weight * $this->qty, $decimals); + case 'priceTotal': + return round($this->price * $this->qty, $decimals); + case 'subtotal': + return round($this->priceTotal - $this->discountTotal, $decimals); + case 'priceTarget': + return round(($this->priceTotal - $this->discountTotal) / $this->qty, $decimals); + case 'taxTotal': + return round($this->subtotal * ($this->taxRate / 100) , $decimals); + case 'total': + return round($this->subtotal + $this->taxTotal, $decimals); case 'model': if (isset($this->associatedModel)) { diff --git a/tests/CartTest.php b/tests/CartTest.php index e48d5b6..7d499da 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1049,7 +1049,7 @@ class CartTest extends TestCase } /** @test */ - public function cart_hast_no_rounding_errors() + public function cart_has_no_rounding_errors() { $cart = $this->getCart(); @@ -1309,6 +1309,26 @@ class CartTest extends TestCase }); } + /** @test */ + public function it_use_correctly_rounded_values_for_totals_and_cart_summary() { + + $this->setConfigFormat(2, ',', ''); + + $cart = $this->getCartDiscount(6); + + $cartItem = $cart->add(new BuyableProduct(1, 'First item', 0.18929), 1000); + $cart->add(new BuyableProduct(2, 'Second item', 4.41632), 5); + $cart->add(new BuyableProduct(3, 'Third item', 0.37995), 25); + + $cart->setGlobalTax(22); + + // check total + $this->assertEquals('253,29', $cart->total()); + + // check that the sum of cart subvalues matches the total (in order to avoid cart summary to looks wrong) + $this->assertEquals($cart->totalFloat(), $cart->subtotalFloat() + $cart->taxFloat()); + } + /** * Get an instance of the cart. * @@ -1325,12 +1345,13 @@ class CartTest extends TestCase /** * Get an instance of the cart with discount. * + * @param int $discount * @return \Gloudemans\Shoppingcart\Cart */ - private function getCartDiscount($discount = 0) + private function getCartDiscount($discount = 50) { $cart = $this->getCart(); - $cart->setGlobalDiscount(50); + $cart->setGlobalDiscount($discount); return $cart; } From 1a34bda8ab37403f054f56994cb5057765306b3d Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Wed, 15 Jan 2020 12:44:58 +0100 Subject: [PATCH 43/52] added CartItem::priceTotal for rounded total (from internal calculation) --- src/Cart.php | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Cart.php b/src/Cart.php index 7a0333e..53bedbd 100644 --- a/src/Cart.php +++ b/src/Cart.php @@ -401,11 +401,11 @@ class Cart } /** - * Get the price of the items in the cart. + * Get the price of the items in the cart (not rounded). * * @return float */ - public function initialFloat() // TODO: rename and use priceTotal + public function initialFloat() { return $this->getContent()->reduce(function ($initial, CartItem $cartItem) { return $initial + ($cartItem->qty * $cartItem->price); @@ -426,6 +426,32 @@ class Cart return $this->numberFormat($this->initialFloat(), $decimals, $decimalPoint, $thousandSeperator); } + /** + * Get the price of the items in the cart (previously rounded). + * + * @return float + */ + public function priceTotalFloat() + { + return $this->getContent()->reduce(function ($initial, CartItem $cartItem) { + return $initial + $cartItem->priceTotal; + }, 0); + } + + /** + * Get the price of the items in the cart as formatted string. + * + * @param int $decimals + * @param string $decimalPoint + * @param string $thousandSeperator + * + * @return string + */ + public function priceTotal($decimals = null, $decimalPoint = null, $thousandSeperator = null) + { + return $this->numberFormat($this->priceTotalFloat(), $decimals, $decimalPoint, $thousandSeperator); + } + /** * Get the total weight of the items in the cart. * From d9cc3e2eb4d3feb1313fdb3280b6eaecd428b037 Mon Sep 17 00:00:00 2001 From: Justin Smith Date: Fri, 17 Jan 2020 10:37:58 -0700 Subject: [PATCH 44/52] Typofix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 612f27a..a6fba0e 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Cart::destroy(); ### Cart::weight() -The `weight()` method can be used to get the weight total of all items in the cart, given there weight and quantity. +The `weight()` method can be used to get the weight total of all items in the cart, given their weight and quantity. ```php Cart::weight(); From 7b29fe376d9c68f5484850277fc62a6d05c5038b Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Sat, 18 Jan 2020 17:29:06 +0100 Subject: [PATCH 45/52] StyleCI --- src/CartItem.php | 4 ++-- tests/CartTest.php | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/CartItem.php b/src/CartItem.php index a7387cc..c2d9724 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -378,7 +378,7 @@ class CartItem implements Arrayable, Jsonable case 'priceTax': return round($this->priceTarget + $this->tax, $decimals); case 'discountTotal': - return round ($this->discount * $this->qty, $decimals); + return round($this->discount * $this->qty, $decimals); case 'weightTotal': return round($this->weight * $this->qty, $decimals); case 'priceTotal': @@ -388,7 +388,7 @@ class CartItem implements Arrayable, Jsonable case 'priceTarget': return round(($this->priceTotal - $this->discountTotal) / $this->qty, $decimals); case 'taxTotal': - return round($this->subtotal * ($this->taxRate / 100) , $decimals); + return round($this->subtotal * ($this->taxRate / 100), $decimals); case 'total': return round($this->subtotal + $this->taxTotal, $decimals); diff --git a/tests/CartTest.php b/tests/CartTest.php index 7d499da..e5624dc 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1310,8 +1310,8 @@ class CartTest extends TestCase } /** @test */ - public function it_use_correctly_rounded_values_for_totals_and_cart_summary() { - + public function it_use_correctly_rounded_values_for_totals_and_cart_summary() + { $this->setConfigFormat(2, ',', ''); $cart = $this->getCartDiscount(6); @@ -1346,6 +1346,7 @@ class CartTest extends TestCase * Get an instance of the cart with discount. * * @param int $discount + * * @return \Gloudemans\Shoppingcart\Cart */ private function getCartDiscount($discount = 50) From bc7a3450834c41b356854c2eb2ab69a137928b1f Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Wed, 29 Jan 2020 00:53:08 +0100 Subject: [PATCH 46/52] readme --- README.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a6fba0e..eaa6f74 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Now you're ready to start using the shoppingcart in your application. ## Overview Look at one of the following topics to learn more about LaravelShoppingcart +* [Important note](#Important note) * [Usage](#usage) * [Collections](#collections) * [Instances](#instances) @@ -33,6 +34,14 @@ Look at one of the following topics to learn more about LaravelShoppingcart * [Events](#events) * [Example](#example) +## Important note + +As all the shopping cart that calculate prices including taxes and discount, also this module could be affected by the "totals rounding issue" ([*](https://stackoverflow.com/questions/13529580/magento-tax-rounding-issue)) due to the decimal precision used for prices and for the results. +In order to avoid (or at least minimize) this issue, in the Laravel shoppingcart package the totals are calculated using the method **"per Row"** and returned already rounded based on the number format set as default in the config file (cart.php). +Due to this **WE DISCOURAGE TO SET HIGH PRECISION AS DEFAULT AND TO FORMAT THE OUTPUT RESULT USING LESS DECIMAL** Doing this can lead to the rounding issue. + +The base price (product price) is left not rounded. + ## Usage The shoppingcart gives you the following methods to use: @@ -245,13 +254,15 @@ You can set the default number format in the config file. ### Cart::initial() -The `initial()` method can be used to get the total price of all items in the cart before discount. +The `initial()` method can be used to get the total price of all items in the cart before applying discount and taxes. + +It could be deprecated in the future. **When rounded could be affected by the rounding issue**, use it carefully or use [Cart::priceTotal()](#Cart::priceTotal()) ```php Cart::initial(); ``` -The method will automatically format the result, which you can tweak using the three optional parameters +The method will automatically format the result, which you can tweak using the three optional parameters. ```php Cart::initial($decimals, $decimalSeparator, $thousandSeparator); @@ -259,6 +270,22 @@ Cart::initial($decimals, $decimalSeparator, $thousandSeparator); You can set the default number format in the config file. +### Cart::priceTotal() + +The `priceTotal()` method can be used to get the total price of all items in the cart before applying discount and taxes. + +```php +Cart::priceTotal(); +``` + +The method return the result rounded based on the default number format, but you can tweak using the three optional parameters + +```php +Cart::priceTotal($decimals, $decimalSeparator, $thousandSeparator); +``` + +You can set the default number format in the config file. + **If you're not using the Facade, but use dependency injection in your (for instance) Controller, you can also simply get the subtotal property `$cart->initial`** ### Cart::count() From 4d5edb1126bd9a5ac8668794f77dbd35804ba352 Mon Sep 17 00:00:00 2001 From: Patrick Date: Thu, 30 Jan 2020 15:21:17 +0100 Subject: [PATCH 47/52] Fix # anchor --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eaa6f74..20d7e89 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Now you're ready to start using the shoppingcart in your application. ## Overview Look at one of the following topics to learn more about LaravelShoppingcart -* [Important note](#Important note) +* [Important note](#important-note) * [Usage](#usage) * [Collections](#collections) * [Instances](#instances) From 2078f119ec5d0ead3c0a6fa94137c77d9acd4e32 Mon Sep 17 00:00:00 2001 From: sartoric <> Date: Wed, 12 Feb 2020 22:42:41 +0100 Subject: [PATCH 48/52] Enable gross price as base price --- src/CartItem.php | 87 ++++++++++++++++++++++++++++++++------------- src/Config/cart.php | 12 +++++++ tests/CartTest.php | 38 ++++++++++++++++++++ 3 files changed, 113 insertions(+), 24 deletions(-) diff --git a/src/CartItem.php b/src/CartItem.php index c2d9724..63589b5 100644 --- a/src/CartItem.php +++ b/src/CartItem.php @@ -7,6 +7,18 @@ use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Arr; +/** + * @property-read mixed discount + * @property-read float discountTotal + * @property-read float priceTarget + * @property-read float priceNet + * @property-read float priceTotal + * @property-read float subtotal + * @property-read float taxTotal + * @property-read float tax + * @property-read float total + * @property-read float priceTax + */ class CartItem implements Arrayable, Jsonable { /** @@ -371,39 +383,66 @@ class CartItem implements Arrayable, Jsonable $decimals = config('cart.format.decimals', 2); switch ($attribute) { - case 'discount': - return $this->price * ($this->discountRate / 100); - case 'tax': - return round($this->priceTarget * ($this->taxRate / 100), $decimals); - case 'priceTax': - return round($this->priceTarget + $this->tax, $decimals); - case 'discountTotal': - return round($this->discount * $this->qty, $decimals); - case 'weightTotal': - return round($this->weight * $this->qty, $decimals); - case 'priceTotal': - return round($this->price * $this->qty, $decimals); - case 'subtotal': - return round($this->priceTotal - $this->discountTotal, $decimals); - case 'priceTarget': - return round(($this->priceTotal - $this->discountTotal) / $this->qty, $decimals); - case 'taxTotal': - return round($this->subtotal * ($this->taxRate / 100), $decimals); - case 'total': - return round($this->subtotal + $this->taxTotal, $decimals); - case 'model': if (isset($this->associatedModel)) { return with(new $this->associatedModel())->find($this->id); } - case 'modelFQCN': if (isset($this->associatedModel)) { return $this->associatedModel; } + case 'weightTotal': + return round($this->weight * $this->qty, $decimals); + } - default: - return; + if (config('cart.gross_price')) { + switch ($attribute) { + case 'priceNet': + return round($this->price / (1 + ($this->taxRate / 100)), $decimals); + case 'discount': + return $this->priceNet * ($this->discountRate / 100); + case 'tax': + return round($this->priceTarget * ($this->taxRate / 100), $decimals); + case 'priceTax': + return round($this->priceTarget + $this->tax, $decimals); + case 'discountTotal': + return round($this->discount * $this->qty, $decimals); + case 'priceTotal': + return round($this->priceNet * $this->qty, $decimals); + case 'subtotal': + return round($this->priceTotal - $this->discountTotal, $decimals); + case 'priceTarget': + return round(($this->priceTotal - $this->discountTotal) / $this->qty, $decimals); + case 'taxTotal': + return round($this->subtotal * ($this->taxRate / 100), $decimals); + case 'total': + return round($this->subtotal + $this->taxTotal, $decimals); + default: + return; + } + } else { + switch ($attribute) { + case 'discount': + return $this->price * ($this->discountRate / 100); + case 'tax': + return round($this->priceTarget * ($this->taxRate / 100), $decimals); + case 'priceTax': + return round($this->priceTarget + $this->tax, $decimals); + case 'discountTotal': + return round($this->discount * $this->qty, $decimals); + case 'priceTotal': + return round($this->price * $this->qty, $decimals); + case 'subtotal': + return round($this->priceTotal - $this->discountTotal, $decimals); + case 'priceTarget': + return round(($this->priceTotal - $this->discountTotal) / $this->qty, $decimals); + case 'taxTotal': + return round($this->subtotal * ($this->taxRate / 100), $decimals); + case 'total': + return round($this->subtotal + $this->taxTotal, $decimals); + default: + return; + } } } diff --git a/src/Config/cart.php b/src/Config/cart.php index a437d69..739265e 100644 --- a/src/Config/cart.php +++ b/src/Config/cart.php @@ -2,6 +2,18 @@ return [ + /* + |-------------------------------------------------------------------------- + | Gross price as base price + |-------------------------------------------------------------------------- + | + | This default value is used to select the method to calculate prices and taxes + | If true the item price is managed as a gross price, so taxes will be calculated by separation/exclusion + | + */ + + 'gross_price' => false, + /* |-------------------------------------------------------------------------- | Default tax rate diff --git a/tests/CartTest.php b/tests/CartTest.php index e5624dc..d530599 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1329,6 +1329,44 @@ class CartTest extends TestCase $this->assertEquals($cart->totalFloat(), $cart->subtotalFloat() + $cart->taxFloat()); } + /** @test */ + public function it_use_gross_price_as_base_price() + { + $cart = $this->getCartDiscount(0); + config(['cart.gross_price' => true]); + + $cartItem = $cart->add(new BuyableProduct(1, 'First item', 100), 2); + + $cart->setGlobalTax(22); + + // check net price + $this->assertEquals(81.97, round($cartItem->priceNet,2)); + } + + /** @test */ + public function it_use_gross_price_and_it_use_correctly_rounded_values_for_totals_and_cart_summary() + { + $this->setConfigFormat(2, ',', ''); + config(['cart.gross_price' => true]); + + $cart = $this->getCartDiscount(6); + + $cartItem = $cart->add(new BuyableProduct(1, 'First item', 0.23093), 1000); + $cart->add(new BuyableProduct(2, 'Second item', 5.38791), 5); + $cart->add(new BuyableProduct(3, 'Third item', 0.46354), 25); + + $cart->setGlobalTax(22); + + // check total + $this->assertEquals('254,12', $cart->total()); + + // check item price total + $this->assertEquals(190, $cartItem->priceTotal); + // check that the sum of cart subvalues matches the total (in order to avoid cart summary to looks wrong) + $this->assertEquals($cart->totalFloat(), $cart->subtotalFloat() + $cart->taxFloat()); + } + + /** * Get an instance of the cart. * From 008b6f42de5f1084fc62cb9739047b017ae186bd Mon Sep 17 00:00:00 2001 From: Patrick Henninger Date: Tue, 18 Feb 2020 14:55:20 +0100 Subject: [PATCH 49/52] SyleCI --- tests/CartTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/CartTest.php b/tests/CartTest.php index d530599..24da3cf 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -1340,7 +1340,7 @@ class CartTest extends TestCase $cart->setGlobalTax(22); // check net price - $this->assertEquals(81.97, round($cartItem->priceNet,2)); + $this->assertEquals(81.97, round($cartItem->priceNet, 2)); } /** @test */ @@ -1366,7 +1366,6 @@ class CartTest extends TestCase $this->assertEquals($cart->totalFloat(), $cart->subtotalFloat() + $cart->taxFloat()); } - /** * Get an instance of the cart. * From 8d583c0f7c4a56e31c9f1dd94e1e9add2517bf01 Mon Sep 17 00:00:00 2001 From: Roy Duineveld Date: Wed, 4 Mar 2020 15:32:13 +0100 Subject: [PATCH 50/52] Laravel 7.x support --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index e871ef2..c503067 100644 --- a/composer.json +++ b/composer.json @@ -16,9 +16,9 @@ } ], "require": { - "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0", - "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0", - "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0" + "illuminate/support": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0||^7.0", + "illuminate/session": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0||^7.0", + "illuminate/events": "5.4.*||5.5.*||5.6.*||5.7.*||5.8.*||^6.0||^7.0" }, "require-dev": { "phpunit/phpunit": "~5.0||~6.0||~7.0||~8.0", From 86d25d9fb8f7aa062d1e444b1b4eea7e751c30e2 Mon Sep 17 00:00:00 2001 From: Patrick Date: Tue, 10 Mar 2020 20:25:16 +0100 Subject: [PATCH 51/52] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 20d7e89..565cad2 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 6. +This is a fork of [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 7. ## Installation From 937a5325a5772b3ef3bbf1c091d4c086438eec00 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sun, 12 Apr 2020 18:56:06 +0200 Subject: [PATCH 52/52] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 565cad2..e4dd980 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Latest Unstable Version](https://poser.pugx.org/bumbummen99/shoppingcart/v/unstable)](https://packagist.org/packages/bumbummen99/shoppingcart) [![License](https://poser.pugx.org/bumbummen99/shoppingcart/license)](https://packagist.org/packages/bumbummen99/shoppingcart) -This is a fork of [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 7. +This is a fork of [Crinsane's LaravelShoppingcart](https://github.com/Crinsane/LaravelShoppingcart) extended with minor features compatible with Laravel 7. An example integration can be [found here](https://github.com/bumbummen99/LaravelShoppingcartDemo). ## Installation