I am following a shopping cart tutorial with Laravel, but even though I've copied his code to the point, it does not work like on the tutorial. Every time you click on a product, the shopping cart quantity SHOULD increment, but it didn't.
I am following the tutorial of Max Schwarzmueller's "Laravel Shopping Cart" which you can find on youtube at: https://www.youtube.com/watch?v=56TizEw2LgI&list=PL55RiY5tL51qUXDyBqx0mKVOhLNFwwxvH. I am stuck at #8.
I am new with php, laravel and sessions. I've tried using facades (e.g. Session::put) instead of "$request->session()->put('cart', $cart)". Printing the session with "dd(session()->all())" does confirm that the correct item got added to the array shopping cart.
In ProductController.php
<?php
namespace App\Http\Controllers;
use Session;
use App\Http\Controllers;
use App\Product;
use App\Cart;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function getIndex()
{
$products = Product::all();
return view('shop.index', ['products' => $products]);
}
public function getAddToCart(Request $request, $id){
$product = Product::find($id);
//check in session if cart already contains product
$oldCart = Session::has('cart') ? Session::get('cart') : null;
//if it did contain products, pass them to constructor
$cart= new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
Session::save();
return redirect()->route('product.index');
}
}
In Cart.php
<?php
namespace App;
use Session;
class Cart
{
public $items = Array();
public $totalQty = 0;
public $totalPrice = 0;
public function _construct($oldCart){
if($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item, $id) {
//default values if item not in cart
$storedItem = [
'qty' => 0,
'price' => $item->price,
'item' => $item
];
//if item is already in shopping cart
if($this->items) {
if(array_key_exists($id, $this->items) ) {
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
}
Every time I click on product it activated the getAddtoCart function of ProductController
<a href="{{ route('product.addToCart', ['id'=> $product->id]) }}">Order</a>
I expect that the totalQty of shopping cart should be incremented every time I click on "order" of every products.
If I click twice on "order" for Poke Ball, the "qty" for this specific item (with id 1) should also increment.
But the totalQty starts from 0, but does not increment more than 1. Also qty for the specific item remains 1.