项目作者: treeStoneIT

项目描述 :
An easy-to-use shopping cart for Laravel
高级语言: PHP
项目地址: git://github.com/treeStoneIT/shopping-cart.git
创建时间: 2019-10-07T01:08:58Z
项目社区:https://github.com/treeStoneIT/shopping-cart

开源协议:MIT License

下载


A Database Driven Shopping Cart for Laravel

Software License
Latest Version on Packagist
Total Downloads
Build Status
StyleCI
Scrutinizer Code Quality

This is a simple shopping cart implementation for Laravel 6/7/8. It automatically serializes your cart to the database and loads the related product models.

Usage

To get started, add the Buyable interface to your model.

  1. use Illuminate\Database\Eloquent\Model;
  2. use Treestoneit\ShoppingCart\Buyable;
  3. use Treestoneit\ShoppingCart\BuyableTrait;
  4. class Product extends Model implements Buyable
  5. {
  6. use BuyableTrait;
  7. }

Make sure you implement the getBuyableDescription and getBuyablePrice methods with the respective product description and product price.

Now you can add products to the cart.

  1. use Treestoneit\ShoppingCart\Facades\Cart;
  2. $product = Product::create(['name' => 'Pizza Slice', 'price' => 1.99]);
  3. $quantity = 2;
  4. Cart::add($product, $quantity);

To retrieve the cart contents:

  1. Cart::content();
  2. // or
  3. Cart::items();

To retrieve the total:

  1. Cart::subtotal();

You can update the quantity of an item in the cart. The first argument is the primary id of the related CartItem.

  1. $item = Cart:content()->first();
  2. Cart::update($item->id, $item->quantity + 5);

Or remove the item completely.

  1. Cart::remove($item->id);

Options

To add item-specific options (such as size or color) to an item in the cart, first register available options in your Buyable instance.

  1. class Product extends Model implements Buyable
  2. {
  3. // ...
  4. public function getOptions(): array
  5. {
  6. return [
  7. 'size' => ['18 inch', '36 inch'],
  8. 'color' => ['white', 'blue', 'black'],
  9. ];
  10. }
  11. }

Then you just pass an associative array as the third parameter of Cart::add.

  1. Cart::add($product, 3, ['color' => 'white']);

Any invalid options will be silently removed from the array.

You can also add or change options of an item currently in the cart by calling Cart::updateOption.

  1. $item = Cart:content()->first();
  2. // Update a single option
  3. Cart::updateOption($item->id, 'color', 'black');
  4. // Update multiple options at once
  5. Cart::updateOptions($item->id, [
  6. 'color' => 'black',
  7. 'size' => '36 inch',
  8. ]);

The options array will be available on the CartItem instance as $item->options.

Attaching to Users

You can attach a cart instance to a user, so that their cart from a previous session can be retrieved. Attaching a cart to a user is acheived by calling the attachTo method, passing in an instance of Illuminate\Contracts\Auth\Authenticatable.

  1. class RegisterController
  2. {
  3. /**
  4. * The user has been registered.
  5. *
  6. * @param \Illuminate\Http\Request $request
  7. * @param mixed $user
  8. * @return mixed
  9. */
  10. protected function registered(Request $request, $user)
  11. {
  12. Cart::attachTo($user);
  13. }
  14. }

Then when the user logs in, you can call the loadUserCart method, again passing the user instance.

  1. class LoginController
  2. {
  3. /**
  4. * The user has been authenticated.
  5. *
  6. * @param \Illuminate\Http\Request $request
  7. * @param mixed $user
  8. * @return mixed
  9. */
  10. protected function authenticated(Request $request, $user)
  11. {
  12. Cart::loadUserCart($user);
  13. }
  14. }

Dependency Injection

If you’re not a facade person, you can use the container to inject the shopping cart instance by type-hinting the Treestoneit\ShoppingCart\CartManager class, or the Treestoneit\ShoppingCart\CartContract interface.

Tax

The shopping cart can calculate the total tax of the items in the cart. Just call

  1. $rate = 13; // The tax rate as a percentage
  2. Cart::tax($rate);

You can also set a default tax rate in the included config file.

  1. // config/shopping-cart.php
  2. 'tax' => [
  3. 'rate' => 6,
  4. ],

Then just call Cart::tax without a parameter.

  1. Cart::tax();

If some of your items have different tax rates applicable to them, or are tax-free, no problem. First modify the config file:

  1. // config/shopping-cart.php
  2. 'tax' => [
  3. 'mode' => 'per-item',
  4. ],

Then, set the tax rate per item by implementing the Taxable interface and defining a getTaxRate method.

  1. use Treestoneit\ShoppingCart\Taxable;
  2. class Product extends Model implements Buyable, Taxable
  3. {
  4. /**
  5. * Calculate the tax here based on a database column, or whatever you will.
  6. *
  7. * @return int|float
  8. */
  9. public function getTaxRate()
  10. {
  11. if ($this->tax_rate) {
  12. return $this->tax_rate;
  13. }
  14. if (! $this->taxable) {
  15. return 0;
  16. }
  17. return 8;
  18. }

Now your items will have their custom tax rate applied to them when calling Cart::tax.

Installation

You can install the package via composer:

  1. composer require treestoneit/shopping-cart

To publish the config file and migrations, run

  1. php artisan vendor:publish --provider="Treestoneit\ShoppingCart\CartServiceProvider"

And run the included database migrations.

  1. php artisan migrate

Testing

  1. composer test

Starter (demo) Repository

If you would like to see a starter/demo implementation using this shopping cart please check out our laravel-commerce repository

Roadmap

Some things I didn’t get around to yet:

  • Clear cart instance which has not been attached to a user when session is destroyed.
  • Add an Artisan command that will clear any unattached carts (these two might be mutually exclusive)
  • Add ability to configure cart merging strategy when loadUserCart is called

Credits

License

The MIT License (MIT). Please see the License File for more information.

Laravel Package Boilerplate

This package was generated using the Laravel Package Boilerplate.