Skip to content

Instantly share code, notes, and snippets.

@ginsengs
Created March 24, 2017 20:44
Show Gist options
  • Save ginsengs/f71332733249ebfabcf859320d783b43 to your computer and use it in GitHub Desktop.
Save ginsengs/f71332733249ebfabcf859320d783b43 to your computer and use it in GitHub Desktop.
Simple Laravel Cart
<?php
namespace App\Models;
use App\Models\Product\Product;
use Illuminate\Support\Facades\Session;
class Cart
{
protected static $collection = [];
public static function add($id, $number)
{
$payload = [
'id' => $id,
'number' => $number
];
if (!self::isItem($id)) {
self::$collection[] = $payload;
Session::push('cart', $payload);
} else {
$currentNumber = self::find($id)['number'];
self::change($id, $currentNumber + $number);
}
}
public static function sub($id, $number)
{
if (self::isItem($id)) {
$currentNumber = self::find($id)['number'];
if ($currentNumber - $number >= 1)
self::change($id, $currentNumber - $number);
}
}
protected static function isItem($id)
{
$cart = Session::get('cart') ? Session::get('cart') : [];
foreach ($cart as $item) {
if ($item['id'] == $id)
return true;
}
return false;
}
protected static function getKeySession($idProduct)
{
$cart = Session::get('cart');
foreach ($cart as $key => $item) {
if ($item['id'] == $idProduct)
return $key;
};
}
public static function change($id, $number)
{
$product = self::find($id);
if ($product) {
$product['number'] = $number;
$keyProduct = self::getKeySession($id);
Session::put("cart.$keyProduct", $product);
}
}
public static function find($id)
{
$cart = Session::get('cart') ? Session::get('cart') : [];
foreach ($cart as $item) {
if ($item['id'] == $id) return $item;
}
}
public static function delete($idProduct)
{
Session::forget('cart.' . self::getKeySession($idProduct));
}
/**
* Количество определенного товара в корзине
* @return integer
*/
public static function getItemAmount($idProduct)
{
return self::find($idProduct)['number'];
}
public static function get()
{
if (self::$collection)
return self::$collection;
$cart = Session::get('cart');
$ids = collect($cart)->map(function ($item) {
return $item['id'];
});
$products = Product::whereIn('id', $ids)->get();
self::$collection = $products;
return $products;
}
public static function totalPrice()
{
return Cart::get()->reduce(function ($carry, $item){
return $carry + $item->price;
});
}
public static function getRawData()
{
return Session::get('cart');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment