Commit fe9f5e90 authored by Artem's avatar Artem

improve cart model and controller

parent f0d39ab7
......@@ -3,7 +3,6 @@
namespace App;
//use Illuminate\Database\Eloquent\Model;
use App\Product;
class Cart /*extends Model*/
{
......@@ -34,19 +33,17 @@ class Cart /*extends Model*/
$this->total_price = $result;
}
public function addItem($product, $id)
public function addItem($id)
{
if (array_key_exists($id, $this->items)) {
$this->items[$id]['qty']++;
} else {
$this->items[$id] = [
'item' => $product,
'qty' => 1
];
}
$this->total_qty++;
$this->total_price += $product->price;
}
public function updateQty($products_qty)
......@@ -57,7 +54,6 @@ class Cart /*extends Model*/
} else {
$this->items[$id]['qty'] = (int)$qty;
$this->updateTotalQty();
$this->updateTotalPrice();
}
}
}
......@@ -66,7 +62,6 @@ class Cart /*extends Model*/
{
unset($this->items[$id]);
$this->updateTotalQty();
$this->updateTotalPrice();
}
public function updateCurrentItems()
......
......@@ -26,9 +26,17 @@ class CartController extends Controller
public function addToCart(Product $product)
{
$product->addItemToCart();
$cart = Session::get('cart');
if (Session::has('cart')) {
$cart = Session::get('cart');
$cart->addItem($product->id);
} else {
$cart = new Cart();
$cart->addItem($product->id);
Session::put('cart', $cart);
}
return $cart->total_qty;
}
public function updateQtyInCart(Request $request)
......@@ -44,7 +52,13 @@ class CartController extends Controller
public function removeFromCart(Product $product)
{
$product->removeItemFromCart();
$cart = Session::get('cart');
$cart->removeItem($product->id);
if (!$cart->total_qty) {
Session::forget('cart');
}
}
public function clearCart()
......
......@@ -21,21 +21,4 @@ class Product extends Model
return route('product.edit', $this);
}
public function addItemToCart()
{
if (Session::has('cart')) {
$cart = Session::get('cart');
$cart->addItem($this, $this->id);
} else {
$cart = new Cart();
$cart->addItem($this, $this->id);
Session::put('cart', $cart);
}
}
public function removeItemFromCart()
{
$cart = Session::get('cart');
$cart->removeItem($this->id);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment