Change variable inside a session Laravel 7

Viewed 87

i want to change the attribute "cantidad" inside my session('cart') through a post form which have a input type="num" that will have the quantity to change on the session.

But i cant change it with success , it doesnt do nothing.

Session Code

$cart = [
        $id => [
            "id" => $product->id,
            "nombre" => $product->nombre,
            "cantidad" => 1,
            "precio" => $product->precio,
            "foto" => $product->imagen1

        ]

Trying to change session attribute

public function updateCart($id , Request $request){

    $cart = session()->get('cart');

    foreach($cart as $index => $product){
        if($product["id"] == $id){
            $producto["cantidad"] = $request->cantidad;
        }
    }

    session()->put('cart' , $cart);
    return view('carrito/carrito');
}

Where im wrong?

Sorry for ask this , im new on this jaja

1 Answers

Arrays in PHP are passed by value, not by reference. In other words, in your foreach loop, you get a copy of your array.

Try this instead:

foreach(array_keys($cart) as $index){
    if($cart[$index]["id"] == $id){
        $cart[$index]["cantidad"] = $request->cantidad;
    }
}

Alternatively, you can make your array be passed by reference with & operator:

foreach($cart as &$product){
    if($product["id"] == $id) {
        $product["cantidad"] = $request->cantidad;
    }
}
Related