2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@oshabz please check my updated answer and let me know, my first code was incorrect given your data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.