GithubHelp home page GithubHelp logo

laravel-shopping-cart's Introduction

Laravel Shopping Cart

GitHub Workflow Status styleci

Packagist Packagist Packagist

Install

Install via composer

composer require melihovv/laravel-shopping-cart

Publish configuration file and migrations

php artisan vendor:publish --provider="Melihovv\ShoppingCart\ServiceProvider"

Run migrations

php artisan migrate

Overview

Usage

Regiser facade in config/app.php

'Cart' => 'Melihovv\ShoppingCart\Facades\ShoppingCart',

or

use Melihovv\ShoppingCart\Facades\ShoppingCart as Cart;

in the below examples.

The shopping cart gives you the following methods to use:

Cart::add()

Add an item to the shopping cart.

$cartItem = Cart::add($id, $name, $price, $quantity);
$cartItem = Cart::add($id, $name, $price, $quantity, [
    'color' => 'white',
]);

Cart::remove()

Remove the item with the specified unique id from the shopping cart. Unique id is used to store items with the same $id, but different $options.

$cartItem = Cart::add($id, $name, $price, $quantity);

// ...

Cart::remove($cartItem->getUniqueId())

Cart::has()

Check if the shopping cart contains the item with the specified unique id.

$cartItem = Cart::add($id, $name, $price, $quantity);

// ...

if (Cart::has($cartItem->getUniqueId())) {
    // Do smth.
}

Cart::get()

Get an item in the shopping cart by its unique id.

$cartItem = Cart::add($id, $name, $price, $quantity);

// ...

$cartItem = Cart::get($cartItem->getUniqueId());

Cart::content()

Get all items in the shopping cart.

Cart::clear()

Clear the shopping cart.

Cart::count()

Return number of items in the shopping cart. This method does not summarize quantities of item. For example, there are 3 books and 1 iPhone in the shopping cart, so this method returns 2.

Cart::getTotal()

Return total price of all items in the shopping cart.

Cart::add(1, 'iPhone 7', 500, 1);
Cart::add(1, 'iPad Pro', 700, 2);
Cart::getTotal(); // return 1900

Instances

The package supports multiple instances of the cart. Some examples:

Cart::instance('shopping')->add('192ao12', 'Product 1', 100, 10);

// Store and get the content of the 'shopping' cart
Cart::store->content();

Cart::instance('wishlist')->add('sdjk922', 'Product 2', 50, 1, ['size' => 'medium']);

// Store and get the content of the 'wishlist' cart
Cart::store()->content();

// If you want to get the content of the 'shopping' cart again
Cart::instance('shopping')->restore()->content();

The default cart instance is called default, so when you're not using instances,Cart::content(); is the same as Cart::instance('default')->content().

Cart::instance()

Set current instance name.

Cart::currentInstance()

Get current instance name.

Storage

Currently there are two possible storage to persist shopping cart:

  • Database
  • Redis

You can choose one by specifying repository class name in config

// config/shopping-cart.php

'repository' => \Melihovv\ShoppingCart\Repositories\ShoppingCartDatabaseRepository::class,
// or
'repository' => \Melihovv\ShoppingCart\Repositories\ShoppingCartRedisRepository::class,

In order to use redis storage you also need to install predis/predis package.

Cart::store()

Persist current shopping cart instance to storage.

Cart::store($user->id);
Cart::instance('cart')->store($user->id);
Cart::instance('wishlist')->store($user->id);

Cart::restore()

Restore shopping cart instance to storage.

Cart::restore($user->id);
Cart::instance('cart')->restore($user->id);
Cart::instance('wishlist')->restore($user->id);

Cart::destroy()

Remove shopping cart instance from storage.

Cart::destroy($user->id);
Cart::instance('cart')->destroy($user->id);
Cart::instance('wishlist')->destroy($user->id);

Coupons

You can easily add discount coupons to shopping cart. Currently there are two types of coupons:

  • FixedDiscountCoupon
  • PercentDiscountCoupon

Related methods:

Cart::addCoupon()

Add coupon to cart.

Cart::addCoupon(new FixedDiscountCoupon($name, $discount));
Cart::addCoupon(new PercentDiscountCoupon($name, 0.1)); // 10% discount

Cart::coupons()

Returns all coupons.

Cart::getTotalWithCoupons()

Returns total price with applied coupons.

Cart::add(1, 'iPhone 7', 500, 1);
Cart::add(1, 'iPad Pro', 700, 2);
Cart::addCoupon(new FixedDiscountCoupon($name, 300));
Cart::getTotal(); // return 1900 - 300 = 1600

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

laravel-shopping-cart's People

Contributors

andrewearls avatar bitw avatar melihovv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-shopping-cart's Issues

Adding item to cart then using Cart::count() on blade view does not work

In my function I add an item to the cart, this works as it should and have done multiple checks to ensure the right data is also being passed in, then I redirect to a cart page and attempt to do Cart::count() > 0 to display information if the cart isnt empty except on the blade it returns the cart as empty?

Can we use in stateless environment?

I wonder who cart is saved . Is it per user ?

Cart::add(1, 'iPhone 7', 500, 1);
Cart::add(1, 'iPad Pro', 700, 2);
Cart::getTotal(); // return 1900

Cart::getTotal() gets total from which cart because we know there can be 100 users each having a cart?

Plz let me know if it is stateless i would like to read code too :)

by stateless i mean just using rest api without session

cart is empty

Something wrong, I am using Laravel 7.

Using this code:

$cartItem = Cart::add('1', 'ProductName', '100', 1);
dd($cartItem);
$cartItems = Cart::content();
dd($cartItems);

I have:

Melihovv\ShoppingCart\CartItem {#1283 ▼
  -uniqueId: "027c91341fd5cf4d2579b49c4b6a90da"
  +id: "1"
  +name: "ProductName"
  +price: 100.0
  +quantity: 1
  +options: []
}

Illuminate\Support\Collection {#404 ▼
  #items: array:1 [▼
    "027c91341fd5cf4d2579b49c4b6a90da" => Melihovv\ShoppingCart\CartItem {#1283 ▼
      -uniqueId: "027c91341fd5cf4d2579b49c4b6a90da"
      +id: "1"
      +name: "ProductName"
      +price: 100.0
      +quantity: 1
      +options: []
    }
  ]
}

but after reload page, cart is empty. Table 'shopping_cart' is empty too.

My repository:
`'repository' => \Melihovv\ShoppingCart\Repositories\ShoppingCartDatabaseRepository::class,

'database' => [

    'connection' => 'mysql',

    'table' => 'shopping_cart',

],`

What's wrong?

Laravel 8.0 Support

This is the best shopping cart package availible.

I am trying to upgrade my app to laravel 8.0 but this package does not support laravel 8.0. yet.
I believe I have fixed this and will be making a PR shortly.

Can you apply the tag "hacktoberfest" to this issue. I am trying to get my Hacktoberfest 2020 T-shirt.
https://hacktoberfest.digitalocean.com/details#maintainers

Update migration to use table config value.

Not sure how this was missed, but the table key in the config is pointless, as this package just generates a shopping_cart table regardless, and only uses the config value when dealing with the database repository.

Whether that is intended or not, probably isn't a good idea, as a minimum of two tables would need to be generated if a custom config table was provided, in order for this to work.

How to resolve? Should just be good to update the migration file to include the config value for the up and down methods.

On the off-side, I'd recommend adding an eloquent model also. This is a Laravel package after all, and most users deal with eloquent rather than the query builder. Would make things a lot easier.

I've been struggling to find a decent cart package, and this is the closest to what I've required believe it or not, so I'd rather put my support into this package, than keep with rolling my own solution. I'm quite shocked that most developers in this Laravel community have not managed to develop a half decent cart package, so props to you for developing this, as it's probably the best one out, and it's super simple behind the scenes.

Update quantity if item is in cart already

Lets say I've called the function below and added item to cart
$cartItem = Cart::add($id, $name, $price, $quantity);
How do I update this particular item if the function is called again?
I'm a bit confused about it.
Is the information stored in the session or what?

Remove from cart

How to remove from cart any object?

you are using

$items = $this->addItemsToCart();
\Cart::remove($items[2]->getUniqueId());

in your tests, but this code not working:

Cart::restore(session()->getId());
Cart::restore('default');
$items = Cart::content();
dd(Cart::remove($items[1]->getUniqueId()));

(ErrorException Undefined offset: 1)

dd($items) shows:

Illuminate\Support\Collection {#422 ▼
  #items: array:1 [▼
    "027c91341fd5cf4d2579b49c4b6a90da" => Melihovv\ShoppingCart\CartItem {#423 ▼
      -uniqueId: "027c91341fd5cf4d2579b49c4b6a90da"
      +id: 1
      +name: "Product 1"
      +price: 120.0
      +quantity: 1
      +options: []
    }
  ]
}

when try use 027c91341fd5cf4d2579b49c4b6a90da statically
dd(Cart::remove('027c91341fd5cf4d2579b49c4b6a90da'));

result is: true but cart has still product..

edit: nvm, just forget about store after remove..
but how get this unique id on existing cart?

Colum ID cannot be null error

My code:

public function store(User $user, Request $request)
{
    // dd($request);
    $id = $request->id;
    $name = $request->name;
    $price = $request->price;

    $contentCart = Cart::instance('shopping')->add($id, $request->name, $request->price, 1);

    if(Cart::has($contentCart->getUniqueId())) {
        Cart::store($user->id)->content();
    }
    // Cart::store($user->id)->content();
    // return redirect()->route('cart.index')->with('success', 'Item was added to your cart');
}

DD() has proven request ID is not null, it just wont store apparently.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.