【问题标题】:Cart does not display items laravel购物车不显示物品 laravel
【发布时间】: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');
  • Button not redirecting的可能重复
  • 您将用户“返回”,而不是重定向到购物车。如果将“back()”替换为“route()”会发生什么?

标签: laravel


【解决方案1】:

我认为这正是“redirect()->back()”应该做的,把你送回你来自的页面。

你应该使用:

redirect('cartRouteName')->with('success', 'Product added to cart successfully!');

将“cartRouteName”替换为您希望将用户重定向到的实际命名路线。

有关重定向到 Laravel 中命名路由的更多信息,请参阅此处:

https://laravel.com/docs/5.8/redirects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2017-11-05
    • 2018-12-04
    • 2015-10-24
    相关资源
    最近更新 更多