购物车不显示商品laravel

时间:2019-08-27 18:12:40

标签: laravel

我有一个订单按钮,该按钮应该将用户重定向到已订购商品的购物车页面

<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::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);转储变量,并输出正确的结果

1 个答案:

答案 0 :(得分:1)

我认为这正是“ redirect()-> back()”所要做的,将您带回到您来自的页面。

您应该使用:

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

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

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

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