-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME
1225 lines (879 loc) · 34.3 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Laravel PHP Framework
[](https://travis-ci.org/laravel/framework)
[](https://packagist.org/packages/laravel/framework)
[](https://packagist.org/packages/laravel/framework)
[](https://packagist.org/packages/laravel/framework)
[](https://packagist.org/packages/laravel/framework)
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, queueing, and caching.
Laravel is accessible, yet powerful, providing tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.
## Official Documentation
Documentation for the framework can be found on the [Laravel website](http://laravel.com/docs).
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](http://laravel.com/docs/contributions).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at [email protected]. All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).
LARAVEL SHOP (Laravel 5.2 Package)
--------------------------------
[](https://packagist.org/packages/amsgames/laravel-shop)
[](https://packagist.org/packages/amsgames/laravel-shop)
[](https://packagist.org/packages/amsgames/laravel-shop)
[](https://packagist.org/packages/amsgames/laravel-shop)
Laravel Shop is flexible way to add shop functionality to **Laravel 5.2**. Aimed to be the e-commerce solution for artisans.
Laravel shop adds shopping cart, orders and payments to your new or existing project; letting you transform any model into a shoppable item.
**Supports**
 
## Contents
- [Scope](#scope)
- [Installation](#installation)
- [Configuration](#configuration)
- [Database Setup](#database-setup)
- [Models Setup](#models)
- [Item](#item)
- [Cart](#cart)
- [Order](#order)
- [Transaction](#transaction)
- [User](#user)
- [Existing Model Conversion](#existing-model-conversion)
- [Dump Autoload](#dump-autoload)
- [Payment Gateways](#payment-gateways)
- [PayPal](#paypal)
- [Omnipay](#omnipay)
- [Usage](#usage)
- [Shop](#shop)
- [Purchase Flow](#purchase-flow)
- [Payment Gateway](#payment-gateway)
- [Checkout](#checkout)
- [Order placement](#exceptions)
- [Payments](#payments)
- [Exceptions](#order-placement)
- [Shopping Cart](#shopping-cart)
- [Adding Items](#adding-items)
- [Removing Items](#removing-items)
- [Placing Order](#placing-order)
- [Cart Methods](#cart-methods)
- [Displaying](#removing-items)
- [Item](#item-1)
- [Order](#order-1)
- [Placing Transactions](#placing-transactions)
- [Order Methods](#order-methods)
- [Events](#events)
- [Handler Example](#event-handler-example)
- [Payment Gateway Development](#payment-gateway-development)
- [Transaction](#transaction-1)
- [Callbacks](#callbacks)
- [Exceptions](#exception)
- [License](#license)
- [Additional Information](#additional-information)
- [Change Log](#change-log)
## Scope
Current version includes:
- Shop Items (transforms existing models into shoppable items that can be added to cart and orders)
- Cart
- Orders
- Transactions
- Payment gateways support
- PayPal
- Events
On the horizon:
- Guest user cart
- Shipping orders
- Coupons
- Product and variations solution
- Backend dashboard
- Frontend templates
## Installation
With composer
```bash
composer require amsgames/laravel-shop
```
Or add
```json
"amsgames/laravel-shop": "0.2.*"
```
to your composer.json. Then run `composer install` or `composer update`.
Then in your `config/app.php` add
```php
Amsgames\LaravelShop\LaravelShopProvider::class,
```
in the `providers` array.
Then add
```php
'Shop' => Amsgames\LaravelShop\LaravelShopFacade::class,
```
in the `aliases` array.
## Configuration
Set the configuration values in the `config/auth.php` file. This package will use them to refer to the user table and model.
Publish the configuration for this package to further customize table names, model namespaces, currencies and other values. Run the following command:
```bash
php artisan vendor:publish
```
A `shop.php` file will be created in your app/config directory.
### Database Setup
Generate package migration file:
```bash
php artisan laravel-shop:migration
```
The command below will generate a new migration file with database commands to create the cart and item tables. The file will be located in `database/migrations`. Add additional fields if needed to fill your software needs.
The command will also create a database seeder to fill shop catalog of status and types.
Create schema in database:
```bash
php artisan migrate
```
Add the seeder to `database/seeds/DatabaseSeeder.php`:
```php
class DatabaseSeeder extends Seeder
{
public function run()
{
Model::unguard();
$this->call('LaravelShopSeeder');
Model::reguard();
}
}
```
Run seeder (do `composer dump-autoload first`):
```bash
php artisan db:seed
```
### Models
The following models must be created for the shop to function, these models can be customizable to fir your needs.
#### Item
Create a Item model:
```bash
php artisan make:model Item
```
This will create the model file `app/Item.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopItemModel;
class Item extends ShopItemModel
{
}
```
The `Item` model has the following main attributes:
- `id` — Item id.
- `sku` — Stock Keeping Unit, aka your unique product identification within your store.
- `price` — Item price.
- `tax` — Item tax. Defaulted to 0.
- `shipping` — Item shipping. Defaulted to 0.
- `currency` — Current version of package will use USD as default.
- `quantity` — Item quantity.
- `class` — Class reference of the model being used as shoppable item. Optional when using array data.
- `reference_id` — Id reference of the model being used as shoppable item. Optional when using array data.
- `user_id` — Owner.
- `displayPrice` — Price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTax` — Tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayShipping` — Tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayName` — Based on the model's item name property.
- `shopUrl` — Based on the model's item route property.
- `wasPurchased` — Flag that indicates if item was purchased. This base on the status set in config file.
- `created_at` — When the item record was created in the database.
- `updated_at` — Last time when the item was updated.
Business definition: Item used as a **cart item** or an **order item**.
#### Cart
Create a Cart model:
```bash
php artisan make:model Cart
```
This will create the model file `app/Cart.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopCartModel;
class Cart extends ShopCartModel
{
}
```
The `Item` model has the following main attributes:
- `id` — Cart id.
- `user_id` — Owner.
- `items` — Items in cart.
- `count` — Total amount of items in cart.
- `totalPrice` — Total price from all items in cart.
- `totalTax` — Total tax from all items in cart, plus global tax set in config.
- `totalShipping` — Total shipping from all items in cart.
- `total` — Total amount to be charged, sums total price, total tax and total shipping.
- `displayTotalPrice` — Total price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalTax` — Total tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalShipping` — Total shipping value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotal` — Total amount value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `created_at` — When the cart record was created in the database.
- `updated_at` — Last time when the cart was updated.
#### Order
Create a Order model:
```bash
php artisan make:model Order
```
This will create the model file `app/Order.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopOrderModel;
class Order extends ShopOrderModel
{
}
```
The `Order` model has the following main attributes:
- `id` — Order id or order number.
- `user_id` — Owner.
- `items` — Items in order.
- `transactions` — Transactions made on order.
- `statusCode` — Status code.
- `count` — Total amount of items in order.
- `totalPrice` — Total price from all items in order.
- `totalTax` — Total tax from all items in order, plus global tax set in config.
- `totalShipping` — Total shipping from all items in order.
- `total` — Total amount to be charged, sums total price, total tax and total shipping.
- `displayTotalPrice` — Total price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalTax` — Total tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalShipping` — Total shipping value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotal` — Total amount value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `created_at` — When the order record was created in the database.
- `updated_at` — Last time when the order was updated.
#### Transaction
Create a Transaction model:
```bash
php artisan make:model Transaction
```
This will create the model file `app/Transaction.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopTransactionModel;
class Transaction extends ShopTransactionModel
{
}
```
The `Order` model has the following main attributes:
- `id` — Order id or order number.
- `order` — Items in order.
- `gateway` — Gateway used.
- `transaction_id` — Transaction id returned by gateway.
- `detail` — Detail returned by gateway.
- `token` — Token for gateway callbacks.
- `created_at` — When the order record was created in the database.
- `updated_at` — Last time when the order was updated.
#### User
Use the `ShopUserTrait` trait in your existing `User` model. By adding `use Amsgames\LaravelShop\Traits\ShopUserTrait` and `use ShopUserTrait` like in the following example:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopUserTrait;
class User extends Model {
use Authenticatable, CanResetPassword, ShopUserTrait;
}
```
This will enable the relation with `Cart` and shop needed methods and attributes.
- `cart` — User's cart.
- `items` — Items (either order or cart).
- `orders` — User's orders.
#### Existing Model Conversion
Laravel Shop package lets you convert any existing `Eloquent` model to a shoppable item that can be used within the shop without sacrificing any existing functionality. This feature will let the model be added to carts or orders. The will require two small steps:
Use the `ShopItemTrait` in your existing model. By adding `use Amsgames\LaravelShop\Traits\ShopItemTrait` and `use ShopItemTrait` like in the following example:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
// MY METHODS AND MODEL DEFINITIONS........
}
```
Add `sku` (string) and `price` (decimal, 20, 2) fields to your model's table. You can also include `name` (string), `tax` (decimal, 20, 2) and `shipping` (decimal, 20, 2), although these are optional. You can do this by creating a new migration:
```bash
php artisan make:migration alter_my_table
```
Define migration to look like the following example:
```php
<?php
class AlterMyTable extends Migration {
public function up()
{
Schema::table('MyCustomProduct', function($table)
{
$table->string('sku')->after('id');
$table->decimal('price', 20, 2)->after('sku');
$table->index('sku');
$table->index('price');
});
}
public function down()
{
// Restore type field
Schema::table('MyCustomProduct', function($table)
{
$table->dropColumn('sku');
$table->dropColumn('price');
});
}
}
```
Run the migration:
```bash
php artisan migrate
```
##### Item name
By default, Laravel Shop will look for the `name` attribute to define the item's name. If your exisintg model has a different attribute assigned for the name, simply define it in a property within your model:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
/**
* Custom field name to define the item's name.
* @var string
*/
protected $itemName = 'product_name';
// MY METHODS AND MODEL DEFINITIONS........
}
```
##### Item url
You can define the URL attribute of the item by setting `itemRouteName` and `itemRouteParams` class properties. In the following example the url defined to show the product's profile is `product/{slug}`, the following changes must be applied to the model:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
/**
* Name of the route to generate the item url.
*
* @var string
*/
protected $itemRouteName = 'product';
/**
* Name of the attributes to be included in the route params.
*
* @var string
*/
protected $itemRouteParams = ['slug'];
// MY METHODS AND MODEL DEFINITIONS........
}
```
### Dump Autoload
Dump composer autoload
```bash
composer dump-autoload
```
### Payment Gateways
Installed payment gateways can be configured and added in the `gateways` array in the `shop.php` config file, like:
```php
'gateways' => [
'paypal' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPal::class,
'paypalExpress' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPalExpress::class,
],
```
#### PayPal
Laravel Shop comes with PayPal support out of the box. You can use PayPal's `Direct Credit Card` or `PayPal Express` payments.
To configure PayPal and know how to use the gateways, please visit the [PayPal Gateway Package](https://github.com/amsgames/laravel-shop-gateway-paypal) page.
#### Omnipay
Install [Omnipay Gateway](https://github.com/amostajo/laravel-shop-gateway-omnipay) to enable other payment services like 2Checkout, Authorize.net, Stripe and to name a few.
You might need to get some extra understanding about how [Omnipay](https://github.com/thephpleague/omnipay) works.
## Usage
### Shop
Shop methods to consider:
Format prices or other values to the price format specified in config:
```php
$formatted = Shop::format(9.99);
// i.e. this will return $9.99 or the format set in the config file.
```
#### Purchase Flow
With Laravel Shop you can customize things to work your way, although we recommend standarize your purchase or checkout flow as following (will explain how to use the shop methods below):

* (Step 1) - User views his cart.
* (Step 2) - Continues into selecting the gateway to use.
* (Step 3) - Continues into feeding the gateway selected with required information.
* (Step 4) - Checkouts cart and reviews cart before placing order.
* (Step 5) - Places order.
#### Payment Gateway
Before any shop method is called, a payment gateway must be set:
```php
// Select the gateway to use
Shop::setGateway('paypal');
echo Shop::getGateway(); // echos: paypal
```
You can access the gateway class object as well:
```php
$gateway = Shop::gateway();
echo $gateway; // echos: [{"id":"paypal"}]
```
#### Checkout
Once a payment gateway has been selected, you can call cart to checkout like this:
```php
// Checkout current users' cart
$success = Shop::checkout();
// Checkout q specific cart
$success = Shop::checkout($cart);
```
This will call the `onCheckout` function in the payment gateway and perform validations. This method will return a bool flag indication if operation was successful.
#### Order Placement
Once a payment gateway has been selected and user has checkout, you can call order placement like:
```php
// Places order based on current users' cart
$order = Shop::placeOrder();
// Places order based on a specific cart
$order = Shop::placeOrder($cart);
```
**NOTE:** `placeOrder()` will create an order, relate all the items in cart to the order and empty the cart. The `Order` model doen't include methods to add or remove items, any modification to the cart must be done before the order is placed. Be aware of this when designing your checkout flow.
This will call the `onCharge` function in the payment gateway and charge the user with the orders' total amount. `placeOrder()` will return an `Order` model with which you can verify the status and retrieve the transactions generated by the gateway.
#### Payments
Payments are handled gateways, this package comes with PayPal out of the box.
You can use PayPal's `Direct Credit Card` or `PayPal Express` payments.
To configure PayPal and know how to use its gateways, please visit the [PayPal Gateway Package](https://github.com/amsgames/laravel-shop-gateway-paypal) page.
#### Exceptions
If checkout or placeOrder had errores, you can call and see the exception related:
```php
// On checkout
if (!Shop::checkout()) {
$exception = Shop::exception();
echo $exception->getMessage(); // echos: error
}
// Placing order
$order = Shop::placeOrder();
if ($order->hasFailed) {
$exception = Shop::exception();
echo $exception->getMessage(); // echos: error
}
```
Critical exceptions are stored in laravel's log.
### Shopping Cart
Carts are created per user in the database, this means that a user can have his cart saved when logged out and when he switches to a different device.
Let's start by calling or creating the current user's cart:
```php
// From cart
$cart = Cart::current();
// Once a cart has been created, it can be accessed from user
$user->cart;
```
Note: Laravel Shop doen not support guest at the moment.
Get the cart of another user:
```php
$userId = 1;
$cart = Cart::findByUser($userId);
```
#### Adding Items
Lest add one item of our test and existing model `MyCustomProduct`:
```php
$cart = Cart::current()->add(MyCustomProduct::find(1));
```
By default the add method will set a quantity of 1.
Instead lets add 3 `MyCustomProduct`;
```php
$cart = Cart::current();
$cart->add(MyCustomProduct::find(1), 3);
```
Only one item will be created per sku in the cart. If an item of the same `sku` is added, just on item will remain but its quantity will increase:
```php
$product = MyCustomProduct::find(1);
// Adds 1
$cart->add($product);
// Adds 3
$cart->add($product, 3);
// Adds 2
$cart->add($product, 2);
echo $cart->count; // echos: 6
$second_product = MyCustomProduct::findBySKU('TEST');
// Adds 2 of product 'TEST'
$cart->add($second_product, 2);
// Count based on quantity
echo $cart->count; // echos: 8
// Count based on products
echo $cart->items->count(); // echos: 2
```
We can reset the quantity of an item to a given value:
```php
// Add 3
$cart->add($product, 3);
echo $cart->count; // echos: 3
// Reset quantity to 4
$cart->add($product, 4, $forceReset = true);
echo $cart->count; // echos: 4
```
#### Adding Unexistent Model Items
You can add unexistent items by inserting them as arrays, each array must contain `sku` and `price` keys:
```php
// Adds unexistent item model PROD0001
$cart->add(['sku' => 'PROD0001', 'price' => 9.99]);
// Add 4 items of SKU PROD0002
$cart->add(['sku' => 'PROD0002', 'price' => 29.99], 4);
```
#### Removing Items
Lest remove our test and existing model `MyCustomProduct` from cart:
```php
$product = MyCustomProduct::find(1);
// Remove the product from cart
$cart = Cart::current()->remove($product);
```
The example below will remove the item completly, but it is possible to only remove a certain quantity from the cart:
```php
// Removes only 2 from quantity
// If the quantity is greater than 2, then 1 item will remain in cart
$cart->remove($product, 2);
```
Arrays can be used to remove unexistent model items:
```php
// Removes by sku
$cart->remove(['sku' => 'PROD0001']);
```
To empty cart:
```php
$cart->clear();
```
These methods can be chained:
```php
$cart->add($product, 5)
->add($product2)
->remove($product3)
->clear();
```
#### Cart Methods
```php
// Checks if cart has item with SKU "PROD0001"
$success = $cart->hasItem('PROD0001');
```
#### Placing Order
You can place an order directly from the cart without calling the `Shop` class, although this will only create the order record in the database and no payments will be processed. Same ad when using `Shop`, the cart will be empty after the order is placed.
```php
// This will create the order and set it to the status in configuration
$order = $cart->placeOrder();
```
Status can be forced in creation as well:
```php
$order = $cart->placeOrder('completed');
```
#### Displaying
Hew is an example of how to display the cart in a blade template:
Items count in cart:
```html
<span>Items in cart: {{ $cart->count }}</span>
```
Items in cart:
```html
<table>
@foreach ($cart->items as $item) {
<tr>
<td>{{ $item->sku }}</td>
<td><a href="{{ $item->shopUrl }}">{{ $item->displayName }}</a></td>
<td>{{ $item->price }}</td>
<td>{{ $item->displayPrice }}</td>
<td>{{ $item->tax }}</td>
<td>{{ $item->quantity }}</td>
<td>{{ $item->shipping }}</td>
</tr>
@endforeach
</table>
```
Cart amount calculations:
```html
<table>
<tbody>
<tr>
<td>Subtotal:</td>
<td>{{ $cart->displayTotalPrice }}</td>
<td>{{ $cart->totalPrice }}</td>
</tr>
<tr>
<td>Shipping:</td>
<td>{{ $cart->displayTotalShipping }}</td>
</tr>
<tr>
<td>Tax:</td>
<td>{{ $cart->displayTotalTax }}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total:</th>
<th>{{ $cart->displayTotal }}</th>
<th>{{ $cart->total }}</th>
</tr>
</tfoot>
</table>
```
### Item
Models or arrays inserted in a cart or order are converted into SHOP ITEMS, model `Item` is used instead within the shop.
Model objects can be retrieved from a SHOP ITEM:
```php
// Lets assume that the first Cart item is MyCustomProduct.
$item = $cart->items[0];
// Check if item has model
if ($item->hasObject) {
$myproduct = $item->object;
}
```
`$item->object` is `MyCustomProduct` model already loaded, we can access its properties and methods directly, like:
```php
// Assuming MyCustomProduct has a types relationship.
$item->object->types;
// Assuming MyCustomProduct has myAttribute attribute.
$item->object->myAttribute;
```
The following shop methods apply to model `Item` or exiting models that uses `ShopItemTrait`:
```php
$item = Item::findBySKU('PROD0001');
$item = MyCustomProduct::findBySKU('PROD0002');
// Quering
$item = Item::whereSKU('PROD0001')->where('price', '>', 0)->get();
```
### Order
Find a specific order number:
```php
$order = Order::find(1);
```
Find orders form user:
```php
// Get orders from specific user ID.
$orders = Order::findByUser($userId);
// Get orders from specific user ID and status.
$canceled_orders = Order::findByUser($userId, 'canceled');
```
#### Placing Transactions
You can place a transaction directly from the order without calling the `Shop` class, although this will only create the transaction record in the database and no payments will be processed.
```php
// This will create the order and set it to the status in configuration
$transaction = $order->placeTransaction(
$gateway = 'my_gateway',
$transactionId = 55555,
$detail = 'Custom transaction 55555'
);
```
#### Order Methods
```php
$completed = $order->isCompleted
// Checks if order is in a specific status.
$success = $order->is('completed');
// Quering
// Get orders from specific user ID.
$orders = Order::whereUser($userId)->get();
// Get orders from specific user ID and status.
$completed_orders = Order::whereUser($userId)
->whereStatus('completed')
->get();
```
#### Order Status Codes
Status codes out of the box:
- `in_creation` — Order status in creation. Or use `$order->isInCreation`.
- `pending` — Pending for payment. Or use `$order->isPending`.
- `in_process` — In process of shipping. In process of revision. Or use `$order->isInProcess`.
- `completed` — When payment has been made and items were delivered to client. Or use `$order->isCompleted`.
- `failed` — When payment failed. Or use `$order->hasFailed`.
- `canceled` — When an order has been canceled by the user. Or use `$order->isCanceled`.
You can use your own custom status codes. Simply add them manually to the `order_status` database table or create a custom seeder like this:
```php
class MyCustomStatusSeeder extends Seeder
{
public function run()
{
DB::table('order_status')->insert([
[
'code' => 'my_status',
'name' => 'My Status',
'description' => 'Custom status used in my shop.',
],
]);
}
}
```
Then use it like:
```php
$myStatusCode = 'my_status';
if ($order->is($myStatusCode)) {
echo 'My custom status work!';
}
```
### Events
Laravel Shop follows [Laravel 5 guidelines](http://laravel.com/docs/5.1/events) to fire events, create your handlers and listeners like you would normally do to use them.
| Event | Description | Data passed |
| ------------- | ------------- | ------------- |
| Cart checkout | Event fired after a shop has checkout a cart. | `id` - Cart Id `success` - Checkout result (boolean) |
| Order placed | Event fired when an order has been placed. | `id` - Order Id |
| Order completed | Event fired when an order has been completed. | `id` - Order Id |
| Order status changed | Event fired when an order's status has been changed. | `id` - Order Id `statusCode` - New status `previousStatusCode` - Prev status |
Here are the events references:
| Event | Reference |
| ------------- | ------------- |
| Cart checkout | `Amsgames\LaravelShop\Events\CartCheckout` |
| Order placed | `Amsgames\LaravelShop\Events\OrderPlaced` |
| Order completed | `Amsgames\LaravelShop\Events\OrderCompleted` |
| Order status changed | `Amsgames\LaravelShop\Events\OrderStatusChanged` |
#### Event Handler Example
An example of how to use an event in a handler:
```php
<?php
namespace App\Handlers\Events;
use App\Order;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Amsgames\LaravelShop\Events\OrderCompleted;
class NotifyPurchase implements ShouldQueue
{
use InteractsWithQueue;