我必须删除购物车上的项目,令人惊讶的是,在实现销毁功能后,Laravel没有显示任何错误(我非常begginer上php
<代码>http://localhost:8000/cart?_token=9XiWI3YPPmkctOEPBsEoAyF4UeAkAG3hJLLXHTl9
查看:
@foreach($products as $product)
<tr>
<td><img src="{{ $product['item']['imagePath'] }}" class="img-cart"></td>
<td><strong style="margin-top: 6px">{{ $product['item']['title'] }}</strong></td>
<td>
<form class="form-inline">
<input class="form-control" type="text" value="{{ $product['qty'] }}" style="margin-right: 20px" >
<form method="POST" action="{{ route('cart.destroy', ['id' => $product['item']['id']]) }}" >
@csrf
{{ method_field('DELETE') }}
<input type="submit" value="Delete" onclick="return confirm('Are you sure?')" class="btn btn-danger" />
</form>
</form>
</td>
<td>${{ $product['price'] }}</td>
</tr>
@endforeach
路线:
Route::get('/add-cart/{id}', [
'uses' => 'ProductController@getAddToCart',
'as' => 'addToCart'
]);
Route::get('/cart', [
'uses' => 'ProductController@getCart',
'as' => 'shoppingCart'
]);
Route::get('/del/{id}', 'ProductController@destroy')->name('cart.destroy');
产品控制器:
/**
*@return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::all();
return view('home', ['products'=> $products]);
}
public function getAddToCart(Request $request, $id)
{
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('home');
}
public function getCart()
{
if (!Session::has('cart')) {
return view('cart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}
public function destroy(Request $request, $id)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->delete($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('cart');
}
您的路由是获取而不是删除。它应该是:
Route::delete('/del/{id}', 'ProductController@destroy')->name('cart.destroy');