mardi 10 novembre 2020

How to add instruction with product in Cart

This is a fully working Cart. It can add products and calculate the quantity and total price. but I want to take instructions from User and add it with the Products in Cart.

This is the body from where I am adding product to Cart.

<form action="">
   @csrf
   <input hidden name="products_id" id="products_id">   // It contains the product id
   <input name="instructions" id="instructions">       // Section from where I need to send instructions with each product
   <button type="submit" class="btn theme-btn">Add to cart</button>
</form>

This is the Controller:

public function getAddToCart(Request $request)
{
    $products = Products::find($request->products_id);
    $instructions = $request->input('instructions');
    $oldCart = Session::has('cart') ? Session::get('cart') : null;
    $cart = new Cart($oldCart);
    $cart->add($products, $products->id, $instructions); // It is sending Product and it's Id in Cart Model

    $request->session()->put('cart', $cart);

    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    return redirect('/');
}

This is the Cart Modal:

public function add($item, $id, $instructions) {
    $storedItem = ['qty' => 0, 'price' => $item->price, 'instructions' => $instructions, 'item' => $item];
    if ($this->items) {
        if (array_key_exists($id, $this->items)) {
            $storedItem = $this->items[$id];
        }
    }
    $storedItem['qty']++;
    $storedItem['price'] = $item->price * $storedItem['qty'];
    $storedItem['instructions'];
    $this->items[$id] = $storedItem;
    $this->totalQty++;
    $this->totalPrice += $item->price;
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire