【问题标题】:Button not redirecting按钮不重定向
【发布时间】:2019-08-28 02:46:10
【问题描述】:

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

<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!');
    }

但是当我单击按钮时,它不会重定向到购物车页面,它会一直加载到同一个位置 我做了

 dd($food); 

在函数上,它输出正确的结果

【问题讨论】:

    标签: laravel


    【解决方案1】:

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

    当您使用return redirect()-&gt;back()-&gt;with... 时,您所做的是将用户返回 重定向到他们来自的页面,在这种情况下是您的Order this 按钮所在的页面。

    所以目前的逻辑是:

    1. 在产品页面上
    2. 用户点击Order this按钮
    3. 产品要么添加到购物车,要么增加
    4. 然后用户被重定向回上一页

    如果您希望用户在单击Order this 按钮时被重定向到另一个页面,您需要将用户重定向到另一个页面或另一个路由,就像这样

    return redirect()->route('View Cart')->with('success', 'Product added to cart successfully!');
    

    或者像这样:

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

    这应该导致以下流程:

    1. 在产品页面上
    2. 用户点击Order this按钮
    3. 产品要么添加到购物车,要么增加
    4. 然后用户被重定向到查看购物车页面

    我不知道你有什么路线,所以以上是一个近似值。

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多