GithubHelp home page GithubHelp logo

laravel-cart's Introduction

THIS REPO IS BEING CONSIDERED FOR OWNERSHIP TRANSFER, PLEASE SEE HERE: #62 (comment)

Laravel Shopping Cart Package

Laravel Facade and Service Provider for Moltin\Cart

Installation

via Composer:

$ composer require moltin/laravel-cart

Add the following to your app/config/app.php to the service providers array:

'Moltin\Cart\CartServiceProvider',

Then add to the aliases array the following:

'Cart' => 'Moltin\Cart\Facade',

You should then be good to go and be able to access the cart using the following static interface:

// Format array of required info for item to be added to basket...
$items = array(
	'id' => 1,
	'name' => 'Juicy Picnic Hamper',
	'price' => 120.00,
	'quantity' => 1
);

// Make the insert...
Cart::insert($items);

// Let's see what we have have in there...
dd(Cart::totalItems());

###Config settings (Optional) Publish the config file with php artisan vendor:publish

return array(
    'storage' => 'session', //session, cache, file

    // Cache
    // Laravel documentation for more information
    'cache_prefix' => 'moltin_cart_',
    'cache_expire' => '-1', //in minutes, -1  permanent caching

    // Filesystem
    // Folder Name inside the Storage Path
    'storage_folder_name' => 'moltin_cart',

    // Identifier
    // With a requestcookie (choose for storage: cache, the session will be expired), the cart could be reloaded from a http request, example: the customer could save his cart link (email, hyperlink) and reopen this later.
    // If there is no request, the cookie will be loaded.
    'identifier' => 'cookie', //cookie, requestcookie

    //Request Cookie
    'requestid' => 'CartID', //http input request identifier, example: your customer/backoffice could reload the cart in your shop controller, /public/shop?CartID=871f0bc18ca76e68bf7c3adf8f9426ef
);

Setting the tax rate for an item

Another key you can pass to your insert method is 'tax'. This is a percentage which you would like to be added onto the price of the item.

In the below example we will use 20% for the tax rate.

Cart::insert(array(
    'id'       => 'foo',
    'name'     => 'bar',
    'price'    => 100,
    'quantity' => 1,
    'tax'      => 20
));

Updating items in the cart

You can update items in your cart by updating any property on a cart item. For example, if you were within a cart loop then you can update a specific item using the below example.

foreach (Cart::contents() as $item) {
    $item->name = 'Foo';
    $item->quantity = 1;
}

Removing cart items

You can remove any items in your cart by using the remove() method on any cart item.

foreach (Cart::contents() as $item) {
    $item->remove();
}

Destroying/emptying the cart

You can completely empty/destroy the cart by using the destroy() method.

Cart::destroy()

Retrieve the cart contents

You can loop the cart contents by using the following method

Cart::contents();

You can also return the cart items as an array by passing true as the first argument

Cart::contents(true);

Retrieving the total items in the cart

Cart::totalItems();

By default this method will return all items in the cart as well as their quantities. You can pass true as the first argument to get all unique items.

Cart::totalItems(true);

Retrieving the cart total

$cart->total();

By default the total() method will return the total value of the cart as a float, this will include any item taxes. If you want to retrieve the cart total without tax then you can do so by passing false to the total() method

Cart::total(false);

Check if the cart has an item

Cart::has($itemIdentifier);

Retreive an item object by identifier

Cart::item($itemIdentifier);

Cart items

There are several features of the cart items that may also help when integrating your cart.

Retrieving the total value of an item

You can retrieve the total value of a specific cart item (including quantities) using the following method.

$item->total();

By default, this method will return the total value of the item plus tax. So if you had a product which costs 100, with a quantity of 2 and a tax rate of 20% then the total returned by this method would be 240.

You can also get the total minus tax by passing false to the total() method.

$item->total(false);

This would return 200.

Check if an item has options

You can check if a cart item has options by using the hasOptions() method.

if ($item->hasOptions()) {
    // We have options
}

Remove an item from the cart

$item->remove();

Output the item data as an array

$item->toArray();

laravel-cart's People

Contributors

byordereurope avatar chrisnharvey avatar djekl avatar fed03 avatar jackmcdade avatar lensfettish avatar outrunthewolf avatar philipbrown avatar ryross avatar theodh 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-cart's Issues

Sorting cart items

Is there any way to sort cart items based on item property? In the current implementation, sorting is based on insert time (identifier). Is there any way I could change this behavior?

Add option with price to Cart::total()

So I like to insert the option 'service fee' similar to tax. Which is a percentage of the price.
$s = Cart::insert(array(
'id' => 1,
'name' => 'Team Registration',
'price' => 234,
'quantity' => 1,
'tax' => 6,
'service_fee' => 3,
'organization' => 'LAX',
'event' => 1));
Service fee should be 3% of price in this case 7.02 (234*0.03). Now, how can I added the extra fee to Cart::total() ?
Thanks!

Updating Cart Contents

When I access the Cart's contents via Cart::contents(true); I can not update values for an item. I believe this is because the "true" keyword returns an array, not an Object.

Am I correct or is my code simply wrong?

Code:

foreach(Cart::contents(true) as $item) {
$item['quantity'] = 6;
}

When I pull back the new Cart::contents(true), it says that the array has the previous "quantity" (5 instead of 6).

Adding multiple items, saving to db

I'm having an issue (or me not understanding) how to to save more than one item to my database.

If i die and dump Cart::contents() i get the following: which shows two items.

      protected 'addModifier' => int 1
      protected 'data' => 
        array (size=11)
          'id' => string '100' (length=3)
          'name' => string 'Beautiful Evening Dress' (length=23)
          'price' => string '35.00' (length=5)
          'quantity' => string '1' (length=1)
          'image' => string 'dtTCkLMT3C7lrYE6b1afd6H1hH5IyJ6hYnPWhQbHwkGgCIfhmaTsP9kUhxUr.jpg' (length=64)
          'path' => string 'category/new-in' (length=15)
          'description' => string 'Beautiful Evening Dress ' (length=24)
          'stock' => string '0' (length=1)
          'delivery' => string '3.99' (length=4)
          'colour' => string 'Black' (length=5)
          'size' => string '22' (length=2)
  '6de83ad2f06a80ee5b06ead51cb74fb5' => 
    object(Moltin\Cart\Item)[137]
      protected 'identifier' => string '6de83ad2f06a80ee5b06ead51cb74fb5' (length=32)
      protected 'store' => 
        object(Moltin\Cart\Storage\LaravelSession)[138]
          protected 'identifier' => null
          public 'id' => string '66f7ef23c389dcafb9394506a5b5d934' (length=32)
      protected 'tax' => 
        object(Moltin\Tax\Tax)[139]
          protected 'percentage' => int 0
          protected 'deductModifier' => int 1
          protected 'addModifier' => int 1
      protected 'data' => 
        array (size=11)
          'id' => string '53' (length=2)
          'name' => string 'Black and Silver Pattern dress with Sequins ' (length=44)
          'price' => string '25.00' (length=5)
          'quantity' => string '1' (length=1)
          'image' => string 'USoWtjCsby50.jpg' (length=16)
          'path' => string 'category/new-in' (length=15)
          'description' => string 'Black and Silver Pattern dress with Sequins ' (length=44)
          'stock' => string '1' (length=1)
          'delivery' => string '3.99' (length=4)
          'colour' => string 'Patterned' (length=9)
          'size' => string '14' (length=2)

So the question is, how do i save these items to the DB?

Troubles with users

Hi, i am trying to implement a shopping cart and i have moltin installed but when i add a producto, it stored for every users, and its suppose to save it only for one user, what can i do? or what i am doing wrong? thanks for the help
psd. sorry for my bad english

Multiple cart instances

Is it possibile to use multiple Cart instances?
I think can be useful to have something like this:

// This works on same instance
Cart::contents();
Cart::instance('default')->contents();

// Another instance
Cart::instance('wishlist')->insert(array(
    'id'       => 'foo',
    'name'     => 'bar',
    'price'    => 100,
    'quantity' => 1,
    'tax'      => 20
));

Cart::instance('wishlist')->contents();

Thoughts?

Cookie domain is null

When using this package the cookie domain is set as default, instead use the session config for the cookie domain to allow use across subdomains

Laravel 4.2 composer update error

hello guys, i had problem over here, i'm using laravel 4.2 currently
i tried to include
"moltin/cart": "dev-master"
then run composer update, and it's work
aftter that i add

'Moltin\Cart\CartServiceProvider', and
'Cart' => 'Moltin\Cart\Facade',

but when i run composer update it says

{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'Moltin\Cart\CartServiceProvider' not found"

how to get current CartID for others

I am using $_COOKIE['cart_identifier'] to get it.
but in laravel ,can moltin use Cookie method to set cart_identifier? so that we can use cookie method get it. or maybe make a method to get that value thanks!

Latest commit from moltin/cart break this package

Hi, after running composer update, I am unable to run my application.

Below is the error

Class Moltin\Cart\Storage\LaravelSession contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Moltin\Cart\StorageInterface::findAll, 
Moltin\Cart\StorageInterface::destroyAll)

Is it possible to not tagging laravel-cart to dev-master ?
I am unable to revert back because this package require the failing build.

Error inside CartServiceProvider.php

Hello,

I'm new user of laravel and moltin, I was trying a tutorial with moltin but i had this error :
FatalErrorException Using $this when not in object context

public function register()
{

    $this->app->singleton('cart', function() {
        return new Cart($this->getStorageService(), $this->getIdentifierService());
    });
}

Please Help !!!

Shipping

How about adding shipping functionality?

Having a cart attribute for base shipping along with a product attribute for per item shipping. The shipping could be set with

$cart->setShipping($value);
$product->setShipping($value);

and retrieved similarly.

The total functions that have "include tax" could also have "include shipping".

... or shipping isn't something this should handle. In that case, can someone suggest a way to approach shipping?

LaravelServiceProvider & PHP 5.3

Using $this in a closure function is not compliant with PHP 5.3 as it is a 5.4 feature. Your packagist package requires >= 5.3.0.

    $this->app->singleton('cart', function() {
        return new Cart($this->getStorageService(), $this->getIdentifierService());
    });

"Your requirements could not be resolved to an installable set of packages."

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for moltin/laravel-cart dev-master -> satisfiable by moltin/laravel-cart[dev-master].
    - moltin/laravel-cart dev-master requires moltin/cart dev-master -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Missing Method getIdentifier()

First let me say this cart seems pretty cool only just installed it for a project we are working on and hopefully it will fit the bill :)

The below method fails when called as its not in the moltin/cart itself.

public function getIdentifier()
{
return $this->identifier;
}

Inserting over an item.

Using session, let's say we have:

$A = ["id" => "example", "quantity" => 5, ...];
// and
$B = ["id" => "example", "quantity" => 11, ...];

If we Cart::insert($A) we see from Cart::contents(true) that we have a quantity of 5.

However, using this same cart - if we Cart::insert($B) then examine the contents we see that we have a quantity of 11 until the script ends. At this point the quantity is once again 5 and the new information is not stored.

If this information were stored then item updates would be much simpler in many cases. I would expect this to either sum (3 in cart -> insert(5) -> 8 in cart) or replace the current quantity. Is this feature intentionally left out?

cart identifier

how can I add item identifier to the current session cookie instead of creating new cookie?

How to refresh cart total when updating

Hi,

First i want to thank you for that great cart.
So the issue is this:
I have cart page where user can view and change all ordered products.
I use jquery $.post to get current quantity and update it in controller.
But when i update or remove product i have to reload the page.
Is there a different way to do this without screen flashing?

Thanks in advance

I made it with adding .done(function( data ) {
} after the $.post()

how to use options?

At bottom of readme I see "hasOptions"... but how to use options in cart? How to add options?

Class 'Moltin\\Cart\\CartServiceProvider' not found in fresh Moltin/Cart installation

Hi,

I wanted to try Moltin/Cart package in my application.
I just added package via Composer and made an update.

Added service provider:
'Moltin\Cart\CartServiceProvider',

Than alias:
'Cart' => 'Moltin\Cart\Facade',

I also made autoload dump.
composer dump-autoload

Now when I try for example to update composer, I'm getting an error:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'Moltin\\Cart\\CartServiceProvider' not found"

I'm getting that error even on a fresh laravel installations.

Error: Cart must implement interface Moltin\Cart\StorageInterface, instance of Illuminate\Support\Facades\Session

Everything works perfect past couple of days. But I got this error today when I am retrieving cart price total using, Cart::total(false).

This is the error message,
"Argument 1 passed to Moltin\Cart\Cart::__construct() must implement interface Moltin\Cart\StorageInterface, instance of Illuminate\Support\Facades\Session given, called in D:\xampp\htdocs\eyepax-piqmo\vendor\moltin\laravel-cart\src\Moltin\Cart\CartServiceProvider.php on line 66 and defined"

I'm using Laravel 4.1.*

Cart::destroy(); doesn't work.

Laravel 5.1
Cart::destroy does not destroy cart.
Interesting thing. It doesn't work at all in Google Chrome.
In Mozilla Firefox it works strange.
Cart::destroy();
dd(Cart::totalItems());
gives me 0, but right after that I comment a string

//Cart::destroy();
dd(Cart::totalItems());

and it shows me an old number of items.
It happens until I clear everything in browser (local storage, cookies, session, ...).

So many people uses your package. Are you still maintain it or not??!

I wrote a big bunch of code and now it seems that package does not work with Laravel 5.1.

Loses session

I'm using the latest Laravel build (4.1) and the contents of the cart arent being saved. If i use your example as shown below it works only when that piece of code is on the current request. If i remove the below and refresh, the cart session is destroyed and not saved. I'd have thought the contents of the cart are saved until removed or the session has expired.

//Format array of required info for item to be added to basket...
$items = array(
    'id' => 1,
    'name' => 'Juicy Picnic Hamper',
    'price' => 120.00,
    'quantity' => 1
);

//Make the insert...
Cart::insert($items);

//Let's see what we have got in their...
dd(Cart::totalItems());

Item tax doesn't take quantity into account...

Hi, Great addon! Really enjoying using it.
I had an issue when viewing the amount of tax on each item, you have not taken quantity of items into account, so when i add 10 of the same item the items tax only shows the value for 1 of these items.
This is also then reflected in the totals.
My proposed fix is below...

Item.php

/**
 * Return the total tax for this item
 * 
 * @return float
 */
public function tax()
{
    return $this->tax->rate($this->price);
}

Should be

/**
 * Return the total tax for this item
 * 
 * @return float
 */
public function tax()
{
    return $this->tax->rate($this->price*$this->quantity);
}

Laravel 4.2

Hello, is there any way to install the package on Laravel 4.2?

Cache storage not save update itens

If you use cache storage and try update quantity (for example) of item using this:

Cart::item($id)->quantity = $qty;

or this:

Cart::update($id, 'quantity', $qty);

the action not commit changes for cache.

For resolve this issue, I suggest change method update in Item.php (src of Moltin) adding this line:

$this->store->insertUpdate($this);

The update method would look like this:

public function update($key, $value = null)
    {
        if (is_array($key)) {

            foreach ($key as $updateKey => $updateValue) {
                $this->update($updateKey, $updateValue);
            }

        } else {

            if ($key == 'quantity' and $value < 1) {
                return $this->remove();
            }

            if ($key == 'tax' and is_numeric($value)) {
                $this->tax = new Tax($value);
            }

            // Update the item
            $this->data[$key] = $value;
            $this->store->insertUpdate($this);


        }
    }

Error Composer Require

Hi , congrats for plugin, I'm did try install via composer your plugin but ins't possible , please verify or composer components, thank's

the trouble ๐Ÿ‘Ž
Your requirements could not be resolved to an installable set of packages.

Problem 1
- moltin/laravel-cart v5.0.1 requires moltin/cart dev-master -> no matching package found.
- moltin/laravel-cart v5.0 requires moltin/cart dev-master -> no matching package found.
- Installation request for moltin/laravel-cart ^5.0 -> satisfiable by moltin/laravel-cart[v5.0, v5.0.1].

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

while using unit test getting error

i may main layout i am using "{{Cart::totalItems(true)}} - {{ Cart::total() }}" getting error "cannot modify header information, header already sent " error in "moltin/cart/identifier/cookie.php:46" ,if i am removing the "{{Cart::totalItems(true)}} - {{ Cart::total() }}" , not getting the error & test successfully run

Storage cache - quantity doesn't work

Hi when i'm changing storage to cache, the quantity in the cart doesn't work. The files in /storage/cache are correctly created. On session storage everything works perfectly.

Updating and inserting more than one item

I have the following which adds to the cart:

      {{ Form::open(['route' => 'cart']) }}
                <input type="hidden" name="path" value="{{ Request::path() }}">
                <input type="hidden" name="image" value="{{ $item->image }}">
                <input type="hidden" name="product" value="{{ $item->name }}">
                <input type="hidden" name="description" value="{{ $item->seo_description }}">
                <input type="hidden" name="qty" value="1">
                <input type="hidden" name="size" value="{{ Session::get('size') }}">
                <input type="hidden" name="colour" value="{{ Session::get('colour') }}">
                <input type="hidden" name="price" value="{{ $item->price }}">
            @if ($item->stock > 0) <button class="btn btn-success">Add to Bag</button>  @else <a href="" class="btn btn-primary">Email us</a> @endif
            {{ Form::close() }}

Then I have this which shows the items of the carts.

  @foreach($items as $item)
                    <tr>
                        <td class="col-sm-8 col-md-6">
                        <div class="media">
                            <span class="thumbnail pull-left"> <img class="media-object" src="/uploads/product-images/{{$item->image}}" style="width: 72px; height: 72px;"> </span>
                            <div class="media-body">
                                <h4 class="media-heading"><a href="{{ $item->path }}">{{ $item->name }}</a></h4>
                                <span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
                            </div>
                        </div></td>
                        <td class="col-sm-1 col-md-1" style="text-align: center">
                        <input type="email" class="form-control" id="exampleInputEmail1" value="1">
                        </td>
                        <td class="col-sm-1 col-md-1 text-center"><strong>&pound;{{ $item->price }}</strong></td>
                        <td class="col-sm-1 col-md-1">
                        </td>
                    </tr>
                    @endforeach
                    <tr>
                        <td>   </td>
                        <td>   </td>
                        <td>   </td>
                        <td><h5>Subtotal</h5></td>
                        <td class="text-right"><h5><strong>&pound;{{ $item->price }}</strong></h5></td>
                    </tr>
                    <tr>
                        <td>   </td>
                        <td>   </td>
                        <td>   </td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>   </td>
                        <td>   </td>
                        <td>   </td>
                        <td><h3>Total</h3></td>
                        <td class="text-right"><h3><strong>&pound;{{ Cart::total(false) }}</strong></h3></td>
                    </tr>
                    <tr>
                        <td>   </td>
                        <td>   </td>
                        <td><a href="/remove/{{ $item->identifier }}" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Remove</a>
Continue Shopping Checkout

But like I said it only shows one item, but yet the amount in ยฃ is correct.
Show what should I be doing? Or what am I doing wrong?

Also a suggestion would be to update the docs a little more with more info like this to show people like me more examples.

Storing In Database

Hi,

Could you please add database option to store the cart contents. I would like to check other people's cart items when a user clicks on "add to cart" so if there's only one of the desired product, second user shouldn't be able to add it to the cart.

Edit: And also is it possible to make it compatible with User model. It would be awesome to get user's cart like User::find($id)->cart().

Great package btw, Thanks!

Trying to make every cart item separate

I'm attempting to modify the cart to list every item individually - even duplicate products.
I'm picking up someone else's project and have been asked to modify it. Totally new to Laravel so I'm out my depth

i found in Cart::insert the check if an item is already in the basket, but I can't understand how to give it a new $itemidentifier if it already exists.

if ($this->has($itemIdentifier)) {
    $item['quantity'] = $this->item($itemIdentifier)->quantity + $item['quantity']; 

I'm guessing i need to modify createItemIdentifier somehow but every attempt so far has just resulted in adding to the cart not adding the item (I think I'm just changing the $itemIdentifier for the existing cart item not creating a new one).
Just looking for a pointer of where to look, please.

Expand the README

Could you please add some instructions for the Facade within the README?

For example, how to set it up, how to initialize it and how to use it across Routes?

Currently I cannot seem to retain any Cart data across the application... and I thought that was the entire point of the Facade?

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.