爲什麼我在我的購物車中添加一些數量時出現錯誤。這是我的錯誤: TokenMismatchExceptionTokenMismatchException在我添加到購物車時,我添加了數量
這是我的觀點:
<div class="specs">
<h4>Details</h4>
<p>{{ $product_info[0]->description }}</p>
<label>Quantity</label>
<div class="quantity">
<form action="{{ route('prodcart',['id' => $product_info[0]->product_id ]) }}" method="post" id="frmaddcart">
<input type="number" name="qty" min="1" max="{{ $product_info[0]->quantity }}" step="1" value="1" readonly>
{{ csrf_field() }}
</form>
</div>
<button id="btnaddCart" class="btn btn-success btn-cart"> ADD TO CART </button>
</div>
我jQuery的提交按鈕:
$('#btnaddCart').click(function(){
$('#frmaddcart').submit();
});
在我看來,我已經把
CSRF_field()
也是我的提交按鈕
,我已經添加jquery提交它在我的控制器。
這裏是我的控制器:
public function addToCart(Request $request, $product_id)
{
$quantity = $request->qty;
$product = DB::table('products')
->select('*')
->where(['products.product_id' => $product_id])
->first();
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->product_id, $quantity);
$request->session()->put('cart', $cart);
return redirect()->route('productlist',['id' => $product->subcategory_id ]);
}
那麼這裏就是我的購物車類:
<?php
namespace App;
class Cart
{
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, $product_id, $quantity) {
$storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
if($this->items) {
if(array_key_exists($product_id, $this->items)) {
$storedItem = $this->items[$product_id];
}
}
$storedItem['qty'] = $quantity;
$storedItem['price'] = $item->price * $storedItem['qty'];
$this->items[$product_id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
}
我猜你提交頁面時出現問題。分享你如何提交頁面? – C2486
@ user2486感謝您的回覆先生。我的提交是在按鈕id =「btnaddCart」和它在jquery –