oshabz
oshabz

Reputation: 139

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"
    ]
   ]

Upvotes: 2

Views: 404

Answers (1)

dparoli
dparoli

Reputation: 9161

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

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).

Upvotes: 2

Related Questions