Skip to content

Commit a356248

Browse files
committed
added ability to a cart for a specific user, improve docs and added examples
1 parent e28f682 commit a356248

File tree

4 files changed

+241
-49
lines changed

4 files changed

+241
-49
lines changed

README.md

Lines changed: 177 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ NOTE: If you are using laravel 5.5, this will be automatically added by its auto
3535
'Cart' => Darryldecode\Cart\Facades\CartFacade::class
3636
```
3737

38+
3. Optional configuration file (useful if you plan to have full control)
39+
```php
40+
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"
41+
```
42+
3843
## HOW TO USE
3944
* [Usage](#usage)
4045
* [Conditions](#conditions)
@@ -45,11 +50,29 @@ NOTE: If you are using laravel 5.5, this will be automatically added by its auto
4550
* [Format Response](#format)
4651
* [Examples](#examples)
4752
* [Using Different Storage](#storage)
48-
* [Changelogs](#changelogs)
4953
* [License](#license)
5054

5155
## Usage
5256

57+
### IMPORTANT NOTE!
58+
By default, the cart has a default sessionKey that holds the cart data. This
59+
also servers as a cart unique identifier which you can use to bind a cart to a specific user.
60+
To override this default session Key, you will just simply call the ```session($sessionKey)``` method
61+
before any other methods.
62+
63+
Example:
64+
65+
```php
66+
$userId // the current login user id
67+
68+
\Cart::session($userId)->add();
69+
\Cart::session($userId)->update();
70+
\Cart::session($userId)->remove();
71+
// and so on..
72+
```
73+
74+
See More Examples below:
75+
5376
Adding Item on Cart: **Cart::add()**
5477

5578
There are several ways you can add items on your cart, see below:
@@ -101,6 +124,10 @@ Cart::add(array(
101124
),
102125
));
103126

127+
// add cart items to a specific user
128+
$userId = auth()->user()->id; // or any string represents user identifier
129+
Cart::session($userId)->add(455, 'Sample Item', 100.99, 2, array());
130+
104131
// NOTE:
105132
// Please keep in mind that when adding an item on cart, the "id" should be unique as it serves as
106133
// row identifier as well. If you provide same ID, it will assume the operation will be an update to its quantity
@@ -148,6 +175,13 @@ Cart::update(456, array(
148175
));
149176
// so with that code above as relative is flagged as false, if the item's quantity before is 2 it will now be 5 instead of
150177
// 5 + 2 which results to 7 if updated relatively..
178+
179+
// updating a cart for a specific user
180+
$userId = auth()->user()->id; // or any string represents user identifier
181+
Cart::session($userId)->update(456, array(
182+
'name' => 'New Item Name', // new item name
183+
'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
184+
));
151185
```
152186

153187
Removing an item on a cart: **Cart::remove()**
@@ -162,6 +196,10 @@ Removing an item on a cart is very easy:
162196
*/
163197

164198
Cart::remove(456);
199+
200+
// removing cart item for a specific user's cart
201+
$userId = auth()->user()->id; // or any string represents user identifier
202+
Cart::session($userId)->remove(456);
165203
```
166204

167205
Getting an item on a cart: **Cart::get()**
@@ -182,6 +220,10 @@ Cart::get($itemId);
182220

183221
// You can also get the sum of the Item multiplied by its quantity, see below:
184222
$summedPrice = Cart::get($itemId)->getPriceSum();
223+
224+
// get an item on a cart by item ID for a specific user's cart
225+
$userId = auth()->user()->id; // or any string represents user identifier
226+
Cart::session($userId)->get($itemId);
185227
```
186228

187229
Getting cart's contents and count: **Cart::getContent()**
@@ -206,6 +248,10 @@ $cartCollection->count();
206248
// transformations
207249
$cartCollection->toArray();
208250
$cartCollection->toJson();
251+
252+
// Getting cart's contents for a specific user
253+
$userId = auth()->user()->id; // or any string represents user identifier
254+
Cart::session($userId)->getContent($itemId);
209255
```
210256

211257
Check if cart is empty: **Cart::isEmpty()**
@@ -217,6 +263,10 @@ Check if cart is empty: **Cart::isEmpty()**
217263
* @return bool
218264
*/
219265
Cart::isEmpty();
266+
267+
// Check if cart's contents is empty for a specific user
268+
$userId = auth()->user()->id; // or any string represents user identifier
269+
Cart::session($userId)->isEmpty();
220270
```
221271

222272
Get cart total quantity: **Cart::getTotalQuantity()**
@@ -228,6 +278,9 @@ Get cart total quantity: **Cart::getTotalQuantity()**
228278
* @return int
229279
*/
230280
$cartTotalQuantity = Cart::getTotalQuantity();
281+
282+
// for a specific user
283+
$cartTotalQuantity = Cart::session($userId)->getTotalQuantity();
231284
```
232285

233286
Get cart subtotal: **Cart::getSubTotal()**
@@ -239,6 +292,9 @@ Get cart subtotal: **Cart::getSubTotal()**
239292
* @return float
240293
*/
241294
$subTotal = Cart::getSubTotal();
295+
296+
// for a specific user
297+
$subTotal = Cart::session($userId)->getSubTotal();
242298
```
243299

244300
Get cart total: **Cart::getTotal()**
@@ -250,6 +306,9 @@ Get cart total: **Cart::getTotal()**
250306
* @return float
251307
*/
252308
$total = Cart::getTotal();
309+
310+
// for a specific user
311+
$total = Cart::session($userId)->getTotal();
253312
```
254313

255314
Clearing the Cart: **Cart::clear()**
@@ -261,6 +320,7 @@ Clearing the Cart: **Cart::clear()**
261320
* @return void
262321
*/
263322
Cart::clear();
323+
Cart::session($userId)->clear();
264324
```
265325

266326
## Conditions
@@ -301,6 +361,7 @@ $condition = new \Darryldecode\Cart\CartCondition(array(
301361
));
302362

303363
Cart::condition($condition);
364+
Cart::session($userId)->condition($condition); // for a speicifc user's cart
304365

305366
// or add multiple conditions from different condition instances
306367
$condition1 = new \Darryldecode\Cart\CartCondition(array(
@@ -357,6 +418,7 @@ NOTE: All cart based conditions should be applied before calling **Cart::getTota
357418
Then Finally you can call **Cart::getTotal()** to get the Cart Total with the applied conditions.
358419
```php
359420
$cartTotal = Cart::getTotal(); // the total will be calculated based on the conditions you ave provided
421+
$cartTotal = Cart::session($userId)->getTotal(); // for a specific user's cart
360422
```
361423

362424
Next is the Condition on Per-Item Bases.
@@ -771,33 +833,138 @@ Using different storage for the carts items is pretty straight forward. The stor
771833
class that is injected to the Cart's instance will only need methods.
772834

773835
Example we will need a wishlist, and we want to store its key value pair in database instead
774-
of the default session. We do this using below:
836+
of the default session.
837+
838+
To do this, we will need first a database table that will hold our cart data.
839+
Let's create it by issuing ```php artisan make:migration create_cart_storage_table```
840+
841+
Example Code:
842+
843+
```php
844+
use Illuminate\Support\Facades\Schema;
845+
use Illuminate\Database\Schema\Blueprint;
846+
use Illuminate\Database\Migrations\Migration;
847+
848+
class CreateCartStorageTable extends Migration
849+
{
850+
/**
851+
* Run the migrations.
852+
*
853+
* @return void
854+
*/
855+
public function up()
856+
{
857+
Schema::create('cart_storage', function (Blueprint $table) {
858+
$table->string('id')->index();
859+
$table->longText('cart_data');
860+
$table->timestamps();
861+
862+
$table->primary('id');
863+
});
864+
}
865+
866+
/**
867+
* Reverse the migrations.
868+
*
869+
* @return void
870+
*/
871+
public function down()
872+
{
873+
Schema::dropIfExists('cart_storage');
874+
}
875+
}
876+
```
877+
878+
Next, lets create an eloquent Model on this table so we can easily deal with the data. It is up to you where you want
879+
to store this model. For this example, lets just assume to store it in our App namespace.
880+
881+
Code:
882+
```php
883+
namespace App;
884+
885+
use Illuminate\Database\Eloquent\Model;
886+
887+
888+
class DatabaseStorageModel extends Model
889+
{
890+
protected $table = 'cart_storage';
891+
892+
/**
893+
* The attributes that are mass assignable.
894+
*
895+
* @var array
896+
*/
897+
protected $fillable = [
898+
'id', 'cart_data',
899+
];
900+
901+
public function setCartDataAttribute($value)
902+
{
903+
$this->attributes['cart_data'] = serialize($value);
904+
}
905+
906+
public function getCartDataAttribute($value)
907+
{
908+
return unserialize($value);
909+
}
910+
}
911+
```
775912

776-
Create a new class for your storage:
913+
Next, Create a new class for your storage to be injected to our cart instance:
777914

778915
Eg.
779916
```
780-
class WishListDBStorage {
917+
class DBStorage {
781918
782919
public function has($key)
783920
{
784-
// your logic here to check if storage has the given key
921+
return DatabaseStorageModel::find($key);
785922
}
786923
787924
public function get($key)
788925
{
789-
// your logic here to get an item using its key
926+
if($this->has($key))
927+
{
928+
return new CartCollection(DatabaseStorageModel::find($key)->cart_data);
929+
}
930+
else
931+
{
932+
return [];
933+
}
790934
}
791935
792936
public function put($key, $value)
793937
{
794-
// your logic here to put an item with key value pair
938+
if($row = DatabaseStorageModel::find($key))
939+
{
940+
// update
941+
$row->cart_data = $value;
942+
$row->save();
943+
}
944+
else
945+
{
946+
DatabaseStorageModel::create([
947+
'id' => $key,
948+
'cart_data' => $value
949+
]);
950+
}
795951
}
796952
}
797953
```
798954

799-
Then in your service provider for your wishlist cart, you replace the storage
800-
to use your custom storage.
955+
To make this the cart's default storage, let's update the cart's configuration file.
956+
First, let us publish first the cart config file for us to enable to override it.
957+
```php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"```
958+
959+
after running that command, there should be a new file on your config folder name ```shopping_cart.php```
960+
961+
Open this file and let's update the storage use. Find the key which says ```'storage' => null,```
962+
And update it to your newly created DBStorage Class, which on our example,
963+
```'storage' => \App\DBStorage::class,```
964+
965+
OR If you have multiple cart instance (example WishList), you can inject the custom database storage
966+
to your cart instance by injecting it to the service provider of your wishlist cart, you replace the storage
967+
to use your custom storage. See below:
801968

802969
```
803970
use Darryldecode\Cart\Cart;
@@ -823,7 +990,7 @@ class WishListProvider extends ServiceProvider
823990
{
824991
$this->app->singleton('wishlist', function($app)
825992
{
826-
$storage = new WishListDBStorage(); <-- Your new custom storage
993+
$storage = new DBStorage(); <-- Your new custom storage
827994
$events = $app['events'];
828995
$instanceName = 'cart_2';
829996
$session_key = '88uuiioo99888';
@@ -840,39 +1007,6 @@ class WishListProvider extends ServiceProvider
8401007
```
8411008

8421009

843-
## Changelogs
844-
845-
**2.4.0
846-
- added new method on a condition: $condition->getAttributes(); (Please see [Conditions](#conditions) section)
847-
848-
**2.3.0
849-
- added new Cart Method: Cart::addItemCondition($productId, $itemCondition)
850-
- added new Cart Method: Cart::getTotalQuantity()
851-
852-
**2.2.1
853-
- bug fixes
854-
855-
**2.2.0
856-
- added new Cart Method: Cart::getConditionsByType($type)
857-
- added new Item Method: Cart::removeConditionsByType($type)
858-
859-
**2.1.1
860-
- when a new product with the same ID is added on a cart and a quantity is provided, it will increment its current quantity instead of overwriting it. There's a chance that you will also need to update an item's quantity but not incrementing it but reducing it, please just see the documentation (Please see Cart::update() section, and read carefully)
861-
862-
**2.1.0
863-
- added new Cart Method: getCalculatedValue($totalOrSubTotalOrPrice)
864-
- added new Item Method: getPriceSum()
865-
866-
**2.0.0 (breaking change)
867-
- major changes in dealing with conditions (Please see [Conditions](#conditions) section, and read carefully)
868-
- All conditions added on per item bases should have now target => 'item' instead of 'subtotal'
869-
- All conditions added on per cart bases should have now target => 'subtotal' instead of 'total'
870-
871-
**1.1.0
872-
- added new method: clearCartConditions()
873-
- added new method: removeItemCondition($itemId, $conditionName)
874-
- added new method: removeCartCondition($conditionName)
875-
8761010
## License
8771011

8781012
The Laravel Shopping Cart is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

0 commit comments

Comments
 (0)