Skip to content

Instantly share code, notes, and snippets.

@simioluwatomi
Created December 19, 2020 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simioluwatomi/9f0f4a0343aaf81e3f54882413d9cbc8 to your computer and use it in GitHub Desktop.
Save simioluwatomi/9f0f4a0343aaf81e3f54882413d9cbc8 to your computer and use it in GitHub Desktop.
Custom Shopping Cart class that calculates weight of items in the cart
<?php
namespace App\Helpers;
use Darryldecode\Cart\Facades\CartFacade;
class Cart
{
/**
* @var bool|CartFacade
*/
private $cart;
public function __construct()
{
$this->cart = CartFacade::session(config('shopping_cart.default_cart_session_key'));
}
/**
* get cart sub total with item conditions applied to each condition.
*
* @return float
*/
public function getSubtotalWithItemConditions()
{
$cart = $this->cart->getContent();
return $cart->sum(function ($item) {
return $item->getPriceSumWithConditions(false);
});
}
/**
* get total weight of items in the cart.
*
* @return int
*/
public function getTotalWeight()
{
$items = $this->cart->getContent();
if ($items->isEmpty()) {
return 0;
}
return $items->sum(function ($item) {
return $item->attributes['weight'] * $item['quantity'];
});
}
/**
* Get coupon conditions applied to the cart.
*
* @return \Darryldecode\Cart\CartCollection
*/
public function getCouponConditions()
{
return $this->cart->getContent()
->pluck('conditions')
->flatten()
->filter(function ($value) {
return $value->getType() == 'coupon';
});
}
/**
* Get the VAT applied on the cart.
*
* @return int
*/
public function getVatCondition()
{
$condition = $this->cart->getCondition('VAT');
return is_null($condition) ? 0 : $condition->getCalculatedValue($this->cart->getSubtotal());
}
}
<?php
namespace App\Http\Controllers;
use App\User;
use App\Product;
use App\Setting;
use App\Helpers\Cart;
use Illuminate\Http\Request;
use Darryldecode\Cart\CartCondition;
use Darryldecode\Cart\Facades\CartFacade;
class ShoppingCartController extends Controller
{
/**
* @var bool|CartFacade
*/
private $cart;
public function __construct()
{
$this->cart = CartFacade::session(config('shopping_cart.default_cart_session_key'));
}
/**
* Add a product to the shopping cart.
*
* @param Request $request
* @param Product $product
*
* @throws \Darryldecode\Cart\Exceptions\InvalidConditionException
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request, Product $product)
{
$request->validate(['quantity' => ['sometimes', 'integer', 'min:1']]);
$attributes = ['weight' => $product->weight];
$vat = Setting::first()->cart_vat;
$tax = new CartCondition([
'name' => 'VAT',
'type' => 'tax',
'target' => 'total',
'value' => "{$vat}%",
'order' => 1,
]);
$this->cart->condition([$tax]);
$discount = new CartCondition([
'name' => 'Category and Subcategory discount',
'type' => 'discount',
'value' => "-{$product->discount}%",
]);
$this->cart->add([
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'quantity' => $request->filled('quantity') ? (int) $request->quantity : 1,
'attributes' => $attributes,
'conditions' => [$discount], // do not remove brackets as it breaks adding more conditions to item
'associatedModel' => $product,
]);
$route = route('cart.index');
toast("Product added to cart. <a href=\"{$route}\"> View Cart</a>", 'success');
return redirect()->back();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @param Cart $cart
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
*/
public function update(Request $request, $id, Cart $cart)
{
$request->validate(['quantity' => ['required', 'integer', 'min:1']]);
$this->cart->update($id, [
'quantity' => [
'relative' => false,
'value' => $request->input('quantity'),
],
]);
return response()->json([
'data' => [
'weight' => $cart->getTotalWeight(),
'tax' => $cart->getVatCondition(),
'total' => $this->cart->getTotal(),
'subtotal' => $this->cart->getSubTotal(),
'count' => $this->cart->getContent()->count(),
],
], 200);
}
}
@Agjohngabriel
Copy link

This is great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment