【发布时间】:2019-12-31 23:02:36
【问题描述】:
我有一个订单按钮,它应该将用户重定向到订购商品的购物车页面
<p class="btn-holder"><a href="{{route('addCart',$food->id) }}" class="btn btn-primary btn-block text-center" role="button" > Order this</a> </p>
这是 web.php 上的 Route
Route::get('add-to-cart/{id}', 'FoodsController@addToCart')->name('addCart');
这是功能addToCart
public function addToCart($id){
$food = Food::find($id);
if(!$food) {
abort(404);
}
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart) {
$cart = [
$id => [
// "productId" => $food->id,
"name" => $food->food_item,
"quantity" => 1,
"price" => $food->price,
]
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// if item not exist in cart then add to cart with quantity = 1
$cart[$id] = [
// "productId" => $food->id,
"name" => $food->food_item,
"quantity" => 1,
"price" => $food->price,
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
但是当我点击按钮时它不会重定向到购物车页面,它会一直加载到同一个位置。
我尝试在 addToCart 函数上使用 dd($food); 转储变量,它输出正确的结果
【问题讨论】:
-
我会创建一条路线来查看购物车并在您需要时重定向到那里,然后在控制器末尾调用
redirect('/cart');。 -
您将用户“返回”,而不是重定向到购物车。如果将“back()”替换为“route(
)”会发生什么?
标签: laravel