PHP code example of mfissehaye / laravel-shop

1. Go to this page and download the library: Download mfissehaye/laravel-shop library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mfissehaye / laravel-shop example snippets


'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
	    'table' => 'users',
        ],


Amsgames\LaravelShop\LaravelShopProvider::class,

'Shop'      => Amsgames\LaravelShop\LaravelShopFacade::class,

class DatabaseSeeder extends Seeder
{

  public function run()
  {
    Model::unguard();

    $this->call('LaravelShopSeeder');

    Model::reguard();
  }

}



namespace App;

use Amsgames\LaravelShop\Models\ShopItemModel;

class Item extends ShopItemModel
{
}



namespace App;

use Amsgames\LaravelShop\Models\ShopCartModel;

class Cart extends ShopCartModel 
{
}



namespace App;

use Amsgames\LaravelShop\Models\ShopOrderModel;

class Order extends ShopOrderModel 
{
}



namespace App;

use Amsgames\LaravelShop\Models\ShopTransactionModel;

class Transaction extends ShopTransactionModel 
{
}



use Amsgames\LaravelShop\Traits\ShopUserTrait;

class User extends Model {

	use Authenticatable, CanResetPassword, ShopUserTrait;

}



use Amsgames\LaravelShop\Traits\ShopItemTrait;

class MyCustomProduct extends Model {

	use ShopItemTrait;

	// MY METHODS AND MODEL DEFINITIONS........

}



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');
		});
	}

}



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........

}



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 

'gateways' => [
    'paypal'            =>  Amsgames\LaravelShopGatewayPaypal\GatewayPayPal::class,
    'paypalExpress'     =>  Amsgames\LaravelShopGatewayPaypal\GatewayPayPalExpress::class,
],

$formatted = Shop::format(9.99);
// i.e. this will return $9.99 or the format set in the config file.

// Select the gateway to use
Shop::setGateway('paypal');

echo Shop::getGateway(); // echos: paypal

$gateway = Shop::gateway();

echo $gateway; // echos: [{"id":"paypal"}] 

// Checkout current users' cart
$success = Shop::checkout();

// Checkout q specific cart
$success = Shop::checkout($cart);

// Places order based on current users' cart
$order = Shop::placeOrder();

// Places order based on a specific cart
$order = Shop::placeOrder($cart);

// 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
}

// From cart
$cart = Cart::current();
// Once a cart has been created, it can be accessed from user
$user->cart;

$userId = 1;

$cart = Cart::findByUser($userId);

$cart = Cart::current()->add(MyCustomProduct::find(1));

$cart = Cart::current();

$cart->add(MyCustomProduct::find(1), 3);

$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

// 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

// 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);

$product = MyCustomProduct::find(1);

// Remove the product from cart
$cart = Cart::current()->remove($product);

// Removes only 2 from quantity
// If the quantity is greater than 2, then 1 item will remain in cart
$cart->remove($product, 2);

// Removes by sku
$cart->remove(['sku' => 'PROD0001']);

$cart->clear();

$cart->add($product, 5)
    ->add($product2)
    ->remove($product3)
    ->clear();

// Checks if cart has item with SKU "PROD0001"
$success = $cart->hasItem('PROD0001');

// This will create the order and set it to the status in configuration
$order = $cart->placeOrder();

$order = $cart->placeOrder('completed');

// Lets assume that the first Cart item is MyCustomProduct.
$item = $cart->items[0];

// Check if item has model
if ($item->hasObject) {
	$myproduct = $item->object;
}

// Assuming MyCustomProduct has a types relationship.
$item->object->types;

// Assuming MyCustomProduct has myAttribute attribute.
$item->object->myAttribute;

$item = Item::findBySKU('PROD0001');

$item = MyCustomProduct::findBySKU('PROD0002');

// Quering
$item = Item::whereSKU('PROD0001')->where('price', '>', 0)->get();

$order = Order::find(1);

// Get orders from specific user ID.
$orders = Order::findByUser($userId);
// Get orders from specific user ID and status.
$canceled_orders = Order::findByUser($userId, 'canceled');

// 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'
);

$completed = $order->isCompleted
// Checks if order is in a specific status.
$success = $order->statusCodeIs('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();

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.',
		    ],
		]);

  }
}

$myStatusCode = 'my_status';

if ($order->statusCodeIs($myStatusCode)) {
	echo 'My custom status work!';
}



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;

    /**
     * Handle the event.
     *
     * @param  OrderPurchased $event
     * @return void
     */
    public function handle(OrderCompleted $event)
    {
        // The order ID
        echo $event->id;

        // Get order model object
        $order = Order::find($event->id);

        // My code here...
    }
}

        'Amsgames\LaravelShop\Events\OrderCompleted' => [
            'App\Handlers\Events\NotifyPurchase',
        ],



namespace Vendor\Package;

use Amsgames\LaravelShop\Core\PaymentGateway;
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;

class GatewayPayPal extends PaymentGateway
{
    /**
     * Called on cart checkout.
     * THIS METHOD IS OPTIONAL, DONE FOR GATEWAY VALIDATIONS BEFORE PLACING AN ORDER
     *
     * @param Order $order Order.
     */
    public function onCheckout($cart)
    {
        throw new CheckoutException('Checkout failed.');
    }

    /**
     * Called by shop to charge order's amount.
     *
     * @param Order $order Order.
     *
     * @return bool
     */
    public function onCharge($order)
    {
        throw new GatewayException('Payment failed.');
        return false;
    }
}

'gateways' => [
    'paypal'              =>  Vendor\Package\GatewayPaypal::class,
],

Shop::setGateway('paypal');

public function onCharge($order)
{
    // The transaction id generated by the provider i.e.
    $this->transactionId = $paypal->transactionId;

    // Custom detail of 1024 chars.
    $this->detail = 'Paypal: success';

    // Order status after method call.
    $this->statusCode = 'in_process';

    return true;
}



namespace Vendor\Package;

use Amsgames\LaravelShop\Core\PaymentGateway;
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;

class GatewayWithCallbacks extends PaymentGateway
{
    /**
     * Called by shop to charge order's amount.
     *
     * @param Order $order Order.
     *
     * @return bool
     */
    public function onCharge($order)
    {

        // Set the order to pending.
        $this->statusCode = 'pending';

        // Sets provider with the callback for successful transactions.
        $provider->setSuccessCallback( $this->callbackSuccess );

        // Sets provider with the callback for failed transactions.
        $provider->setFailCallback( $this->callbackFail );

        return true;
    }

    /**
     * Called on callback.
     *
     * @param Order $order Order.
     * @param mixed $data  Request input from callback.
     *
     * @return bool
     */
    public function onCallbackSuccess($order, $data = null)
    {
        $this->statusCode     = 'completed';

        $this->detail         = 'successful callback';

        $this->transactionId  = $data->transactionId;

        // My code...
    }

    /**
     * Called on callback.
     *
     * @param Order $order Order.
     * @param mixed $data  Request input from callback.
     *
     * @return bool
     */
    public function onCallbackFail($order, $data = null)
    {
        $this->detail       = 'failed callback';

        // My code...
    }
}
bash
php artisan vendor:publish
bash
php artisan laravel-shop:migration
bash
php artisan migrate
bash
php artisan db:seed
bash
php artisan make:model Item
bash
php artisan make:model Cart
bash
php artisan make:model Order
bash
php artisan make:model Transaction
bash
php artisan migrate
bash
composer dump-autoload