doukengzi3517 2016-11-26 17:16
浏览 28

Laravel会话无法正常工作

I need to increase the value of the variable when i click on a button but the the value is always one. i had clicked the button to more than five times but still the result is always 1.please see the attached image.

my cart class

class Cart
{
    public $totalQuantity = 0;


    public function __construct($oldCart)
    {
        if ($oldCart) {

            $this->totalQuantity = $oldCart->totalQuantity;
        }

    }

    public function add()
    {
        $this->totalQuantity++;

    }
}

controller method

public function getAddToCart(Request $request,$id){
    $oldCart=null;
    //code that i added now to check which returns null
     dd($request->session()->get('cart'));

    if($request->session()->pull('cart')) {
        $oldCart=$request->session()->pull('cart') ;
    }

    $cart=new Cart($oldCart);
    $cart->add();

    $request->session()->push('cart',$cart);
    dd($request->session()->pull('cart'));

    return redirect()->back();
}

following is the image

enter image description here

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-11-26 17:43
    关注

    Laravel doc:

    The pull method will retrieve and delete an item from the session in a single statement

    So if you pull it in the if statetment than the second pull has nothing to offer you as you already deleted it :). You should use get instead, or pull it directly in the $oldCart variable.

    Oh and also if you use push method it is stored as an array so your code should look like this:

    $oldCart = $request->session()->pull('cart');
    
    if ($oldCart) {
        $cart = new Cart($oldCart[0]);
    } else {
        $cart = new Cart(null);
    }
    $cart->add();
    
    $request->session()->push('cart',$cart);
    

    or even better like this:

    $oldCart = null;
    
    if ($request->session()->has('cart')) {
        $oldCart = $request->session()->get('cart');
    }
    
    $cart = new Cart($oldCart);
    $cart->add();
    
    $request->session()->put('cart',$cart);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程