简体   繁体   中英

laravel updating value in session array

I am building a shopping cart using laravel and I want to update quantity in my session array.

i have used this link

How to update a single value in a Laravel Session Array?

but it did not work for me.

  foreach($request->session()->get('shopping_cart') as $value){
    if($value['code'] == $request->product_id){
        echo $value['code'];
        $value['quantity'] = $request->qty_val;
        echo $value['quantity'].'<br />';
        break;
    }
  }

  dd($request->session()->get('shopping_cart'));

 array:2 [▼
     "" => array:5 [▼
     "name" => "Fiona Nicholson"
     "code" => null
     "price" => "848"
     "quantity" => "1"
     "image" => "product_pics/1566371659.jpeg"
    ]
   "sdfwef" => array:5 [▼
      "name" => "Quentin Bryant"
      "code" => "sdfwef"
      "price" => "713"
      "quantity" => "1"
      "image" => "product_pics/1566371616.jpg"
    ]
   ]

To change a value inside a session array it's better to use session()->put() with dot notation instead of passing by reference, ie:

foreach($request->session()->get('shopping_cart') as $key => $value){
    if($value['code'] == $request->product_id){
        $request->session()->put("shopping_cart.$key.quantity", $request->qty_val);
        break;
    }
}

BTW you can use the session() helper, like this:

foreach(session('shopping_cart') as $key => $value){
    if($value['code'] == $request->product_id){
        session(["shopping_cart.$key.quantity" => $request->qty_val]);
        break;
    }
}

Using the helper with an array as argument, session([$key => $value]) is the same of using session()->put($key, $value) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM