This is my model code, and what I'm trying to get is the number of products that a user wants to add to his cart (quantity). My problem is how do I pass the value that I'm getting in the controller through a request to my model because it's there where the data is being processed.
This is my model file. Here's how the quantity is processed and summed.
Cart.php
class Cart extends Model
{
public $items = null;
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)
{
$storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
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;
}
}
Here you can see how I'm getting the quantity from the view. I made a $dd to it and it's passing correctly the quantity
ProductController
public function addCart(Request $request) {
$id = request('product_id');
$qty = request('qty');
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $id, $qty);
$request->session()->put('cart', $cart);
return redirect()->route('user.cart');
}
This is a part of the view. There you can see how I created a form for passing the data.
Show.blade View
<form action="{{ route('user.addCart') }}">
<h6 class="text-muted">Qty :</h6>
<select name="qty" id="qty" class="mr-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<input type="hidden" name="product_id" value="{{ $product->id }}">
<button type="submit" class="btn btn-primary" style="border-radius: 20px;" role="button">Add to <i class="fas fa-shopping-cart"></i></button>
</form>