{"id":21089778,"url":"https://github.com/freshbitsweb/laravel-cart-manager","last_synced_at":"2025-04-04T07:09:40.274Z","repository":{"id":27786202,"uuid":"115199831","full_name":"freshbitsweb/laravel-cart-manager","owner":"freshbitsweb","description":"Managing the cart in your Laravel/E-commerce application is a breeze","archived":false,"fork":false,"pushed_at":"2024-03-01T22:33:06.000Z","size":157,"stargazers_count":228,"open_issues_count":9,"forks_count":33,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-03-28T06:11:07.806Z","etag":null,"topics":["cart-data","cart-manager","ecommerce","laravel","laravel-5-package","laravel-6-package","laravel-shopping-cart","php7","shipping-charges","shopping-cart"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/freshbitsweb.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-12-23T14:13:42.000Z","updated_at":"2025-02-11T21:33:46.000Z","dependencies_parsed_at":"2024-06-18T21:40:33.593Z","dependency_job_id":null,"html_url":"https://github.com/freshbitsweb/laravel-cart-manager","commit_stats":{"total_commits":103,"total_committers":10,"mean_commits":10.3,"dds":"0.12621359223300976","last_synced_commit":"d9ae1a099522f14454585f53fabba303948f4a9d"},"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freshbitsweb%2Flaravel-cart-manager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freshbitsweb%2Flaravel-cart-manager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freshbitsweb%2Flaravel-cart-manager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freshbitsweb%2Flaravel-cart-manager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/freshbitsweb","download_url":"https://codeload.github.com/freshbitsweb/laravel-cart-manager/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247135147,"owners_count":20889421,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cart-data","cart-manager","ecommerce","laravel","laravel-5-package","laravel-6-package","laravel-shopping-cart","php7","shipping-charges","shopping-cart"],"created_at":"2024-11-19T21:31:28.665Z","updated_at":"2025-04-04T07:09:40.251Z","avatar_url":"https://github.com/freshbitsweb.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Latest Stable Version](https://poser.pugx.org/freshbitsweb/laravel-cart-manager/v/stable)](https://packagist.org/packages/freshbitsweb/laravel-cart-manager)\n[![Total Downloads](https://poser.pugx.org/freshbitsweb/laravel-cart-manager/downloads)](https://packagist.org/packages/freshbitsweb/laravel-cart-manager)\n[![License](https://poser.pugx.org/freshbitsweb/laravel-cart-manager/license)](https://packagist.org/packages/freshbitsweb/laravel-cart-manager)\n[![StyleCI](https://styleci.io/repos/115199831/shield?branch=master)](https://styleci.io/repos/115199831)\n[![Buy us a tree](https://img.shields.io/badge/Buy%20me%20a%20tree-%F0%9F%8C%B3-lightgreen?style=flat-square)](https://plant.treeware.earth/freshbitsweb/laravel-cart-manager)\n\n# Cart Manager (Laravel 5.5 to Laravel 10.x)\nLet's make the cart management with Laravel a breeze.\n\n## Just another shopping cart package?\nThere are a few well maintained shopping cart packages available but I wanted to have a solution which feels like *the Laravel way* and is more coupled with the database and provides additional functionality like **shipping charges**, **discount**, **tax**, **total**,  **round off**, **guest carts**, etc. *out-of-box* while staying a very easy to use package.\n\n## Why/when to use?\nLet us decide when this package should be used:\n\n1. You are looking for an easy to use solution which provides cart feature for users as well as guests.\n2. You want to make sure that the carting can work via APIs as well to support mobile applications.\n3. You want features like Shipping charges, tax, discount, round off, etc.\n4. You want to store cart data in Database, session or at a custom place.\n5. You like using the packages which are more like [the Laravel way](https://laravelshift.com/opinionated-laravel-way-shift)\n\n## Requirements\n| PHP    | Laravel | Package |\n|--------|---------|---------|\n| 8.0+   | 10.x    | v1.6.0  |\n| 8.0+   | 9.x     | v1.5.0  |\n| 7.3+   | 8.x     | v1.4.0  |\n| \u003c7.3   | 7.x     | v1.3.0  |\n| \u003c7.2.5 | 6.x     | v1.2.0  |\n\n## Installation\n\n1) Install the package by running this command in your terminal/cmd:\n```\ncomposer require freshbitsweb/laravel-cart-manager\n```\n\n2) Import config file by running this command in your terminal/cmd:\n```\nphp artisan vendor:publish --tag=laravel-cart-manager-config\n```\n\n3) Import migrations files by running these commands in your terminal/cmd:\n```\nphp artisan vendor:publish --tag=laravel-cart-manager-migrations\nphp artisan migrate\n```\n\n4) Add a trait to the model(s) of cart items:\n\n```php\n\u003c?php\n\nnamespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Freshbitsweb\\LaravelCartManager\\Traits\\Cartable;\n\nclass Product extends Model\n{\n    use Cartable;\n    // ...\n}\n```\n\n\n## Usage - As Easy as 1 2 3\n```php\n// Add to cart\n$cart = Product::addToCart($productId);\n\n// Remove from cart\n$cart = cart()-\u003eremoveAt($cartItemIndex);\n\n// Apply discount\n$cart = cart()-\u003eapplyDiscount($percentage);\n\n// Fetch cart\n$cart = cart()-\u003etoArray();\n```\n\n## Demo Repository\n\nThe repository with the demo of using this package can be found at - https://github.com/freshbitsweb/laravel-cart-manager-demo\n\n## Table of contents\n* [Configuration Options](#configuration-options)\n* [Drivers](#drivers)\n* Using the Package\n    * [Cart Management](#cart-management)\n    * [Fetching Cart Data](#fetching-cart-data)\n    * [Discounts](#discounts)\n* Advanced\n    * [Updates in Item Prices](#updates-in-item-prices)\n    * [Using With API](#using-with-api)\n    * [Events](#events)\n    * [Commands](#commands)\n\n## Configuration Options\n\n`cart_manager.php` file contains the following config options for the package:\n\n1. **driver :** *(default: DatabaseDriver)*\nThe [driver](#drivers) that should be used to store and retrieve cart details. You can use existing ones or create your own.\n\n2. **auth_guard :** *(default: web)*\nThe authentication guard that should be used to identify the logged in customer. This package can store carts for guest users as well as logged in users.\n\n3. **shipping_charges :** *(default: 10)*\nThe amount that should be applied as shipping of the order.\n\n4. **shipping_charges_threshold :** *(default: 100)*\nThe minimum order amount to avoid the shipping charges. Take a note that order amount is calculated as subtotal of the cart items - discount amount.\n\n5. **tax_percentage :** *(default: 6%)*\nTax is applied on subtotal of the cart items - discount amount + shipping charges and rounded to 2 decimals.\n\n6. **round_off_to :** *(default: 0.05)*\nYou may wish to round of the order amount to the nearest decimal point. Options are (0 or 0.05 or 0.1 or 0.5 or 1)\n\n7. **cookie_name :** *(default: cart_identifier)*\nThe name of the cookie that this package stores to identify the guests of the web app and store their cart data.\n\n8. **cookie_lifetime :** *(default: 1 week)*\nNumber of minutes for which the cart cookie should be valid in customer's browser.\n\n9. **LC_MONETARY :** *(default: en_US.UTF-8)*\nThis option is used to display the various totals of the cart with a currency symbol. We use php's native [money_format()](//php.net/manual/en/function.money-format.php) function to display currency with amount.\n\n10. **cart_data_validity :** *(default: 1 week) (Database driver only)*\nYou may wish to remove old/invalid cart data from the database. You can specify the validity period and run/schedule the [ClearCartDataCommand](#commands) for the same.\n\n**[⬆ back to top](#table-of-contents)**\n\n## Drivers\n\nYou can  set the driver that should be used to store and retrieve cart details in the `cart_manager.php` config file. You can use existing ones or create your own driver.\n\n### Database Driver\n\nDatabase driver stores the cart data in 2 tables: `carts` and `cart_items`.  You can also remove stale data by running `ClearCartDataCommand`.\n\nUsing this driver allows you to store cart data on server and customer can be displayed the same cart across channels i.e. Mobile app, website, etc.\n\n### Session Driver\n\nThis driver stores the cart data in the session according to the [session driver](https://laravel.com/docs/5.6/session#introduction). This driver does not support cart management for guests via API as we cannot have a uniform way to track the user.\n\n**[⬆ back to top](#table-of-contents)**\n\n## Cart Management\n\nAll of these operations return full cart data with items.\n\n### Add to cart\n```\n/**\n * Add to cart\n *\n * @return json\n */\n public function addToCart()\n{\n    return Product::addToCart(request('productId'));\n}\n```\n\n### Remove from cart\n```\n/**\n * Remove from cart\n *\n * @return json\n */\npublic function removeFromCart()\n{\n    return cart()-\u003eremoveAt(request('cartItemIndex'));\n}\n```\n\n### Increment/decrement quantity of a cart item\n```\n/**\n * Increment cart item quantity\n *\n * @return json\n */\npublic function incrementCartItem()\n{\n    return cart()-\u003eincrementQuantityAt(request('cartItemIndex'));\n}\n\n/**\n * Decrement cart item quantity\n *\n * @return json\n */\npublic function decrementCartItem()\n{\n    return cart()-\u003edecrementQuantityAt(request('cartItemIndex'));\n}\n```\n\n### Update user input quantity of a cart item\n```\n/**\n * Update user input quantity.\n *\n * @return json\n */\npublic function cartItemQuantitySet()\n{\n    return cart()-\u003esetQuantityAt(request('cartItemIndex'), request('cartQuantity'));\n}\n\n```\n\n### Clear cart\n```\n/**\n * Clear Cart\n *\n * @return json\n */\npublic function clearCart()\n{\n    return cart()-\u003eclear();\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Fetching Cart Data\n\n### Get complete cart details\n```\n$cart = cart()-\u003etoArray();\n```\n\n### Get cart attributes\n```\n$cartAttributes = cart()-\u003edata();\n```\n\n### Get cart attributes with currency amount\n```\n$cartTotals = cart()-\u003etotals();\n```\n\n### Get cart individual attributes\nCart has following attributes: `subtotal`, `discount`, `discountPercentage`, `couponId`, `shippingCharges`, `netTotal`, `tax`, `total`, `roundOff`, `payable`.\n\nYou can access any of them using a getter method. For example,\n\n```\n$subtotal = cart()-\u003egetSubtotal();\n```\n\n### Get cart items\n```\n$cartItems = cart()-\u003eitems();\n```\n\n### Get cart items with currency amount\n```\n$cartItems = cart()-\u003eitems($displayCurrency = true);\n```\n\n![](/images/fetching-data.png)\n\n**[⬆ back to top](#table-of-contents)**\n\n## Discounts\n\n### Apply percentage discount\n```\n$cart = cart()-\u003eapplyDiscount($percentage);\n```\n\n### Apply flat discount\n```\n$cart = cart()-\u003eapplyFlatDiscount($discountAmount);\n```\n\n![](/images/apply-discount.png)\n\n**[⬆ back to top](#table-of-contents)**\n\n## Updates in Item Prices\n\nAs this package stores the details of the cart items in a separate table or session, the cart data will not be updated if you update, price, name or image of the cart items.\n\nIf you update any of the item details regularly, we suggest you to run the following code before the final checkout to make sure that order totals are up-to-date as per the latest prices.\n\n```\ncart()-\u003erefreshAllItemsData();\n```\n\nThis code will go through each cart item and update to fresh details.\n\n**[⬆ back to top](#table-of-contents)**\n\n## Using With API\n\n**Note:** This feature is for Database driver only.\n\nThis package uses the cookies and sessions to maintain cart data during page reloads. As the APIs are stateless, we cannot use them to do the same.\n\nTo solve the issue, you can manually set the authenticated user id to maintain the cart data.\n\n```\ncart()-\u003esetUser($userId);\n```\n\nRunning this code will tell the package to assign the cart data to the specified user.\n\n**Note:** Guests cannot manage their carts via API as we cannot have a uniform way to track the user.\n\n**[⬆ back to top](#table-of-contents)**\n\n## Events\n\nWorking with Laravel, how can we forget events?\n\nThis package fires various cart related events which you can listen to for any application updates.\n\n1. CartCreated\n-\u003e Fired when cart is created for the session for the first time and contains the full cart data in the variable `$cartData`.\n\n2. CartItemAdded\n-\u003e Fired when an item is added to the cart and contains the new item Eloquent model object in the variable `$entity`.\n\n3. CartItemRemoved\n-\u003e Fired when an item is removed from the cart and contains the new item Eloquent model object in the variable `$entity`.\n\n4. DiscountApplied\n-\u003e Fired when discount if applied to the cart and contains the full cart data in the variable `$cartData`.\n\n5. CartCleared\n-\u003e Fired when the cart is cleared.\n\n### Sample Usage\n\nAdd the event and listener entry in the `EventServiceProvider` class\n```\nprotected $listen = [\n\t'Freshbitsweb\\LaravelCartManager\\Events\\CartCreated' =\u003e [\n\t\t'App\\Listeners\\LogCartCreated',\n\t],\n];\n```\n\nCreate respective listener:\n```\n\u003c?php\n\nnamespace App\\Listeners;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Freshbitsweb\\LaravelCartManager\\Events\\CartCreated;\n\nclass LogCartCreated\n{\n\t/**\n\t * Handle the event.\n\t *\n\t * @param CartCreated $event\n\t * @return void\n\t */\n\tpublic function handle(CartCreated  $event)\n\t{\n\t\tLog::info('cart', [$event-\u003ecartData]);\n\t}\n}\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## Commands\n\n**Note:** This is required for Database driver only.\n\nYou may wish to remove old/invalid cart data from the database.\n\nSchedule the ClearCartDataCommand for the same.\n\n```\nprotected function schedule(Schedule $schedule)\n{\n    $schedule-\u003ecommand('lcm_carts:clear_old')-\u003edaily();\n}\n```\n\nThis will delete the old/invalid data which is considered based on the `cart_data_validity` config option.\n\n**[⬆ back to top](#table-of-contents)**\n\n## Tests\nRun this command to run the tests of the package:\n```\ncomposer test\n```\n\n## Authors\n\n* [**Gaurav Makhecha**](https://github.com/gauravmak) - *Initial work*\n\nSee also the list of [contributors](https://github.com/freshbitsweb/laravel-cart-manager/graphs/contributors) who participated in this project.\n\n**[⬆ back to top](#table-of-contents)**\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details\n\n## Treeware\n\nYou're free to use this package, but if it makes it to your production environment I would highly appreciate you buying the world a tree.\n\nIt’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to \u003ca href=\"https://www.bbc.co.uk/news/science-environment-48870920\"\u003eplant trees\u003c/a\u003e. If you contribute to our forest you’ll be creating employment for local families and restoring wildlife habitats.\n\nYou can buy trees at for our forest here [offset.earth/treeware](https://plant.treeware.earth/freshbitsweb/laravel-cart-manager)\n\nRead more about Treeware at [treeware.earth](http://treeware.earth)\n\n## Special Thanks to\n\n* [Laravel](https://laravel.com) Community\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffreshbitsweb%2Flaravel-cart-manager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffreshbitsweb%2Flaravel-cart-manager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffreshbitsweb%2Flaravel-cart-manager/lists"}