0

I'm using Laravel 5.5.19 and recently encountered an unpleasant situation. I have a few forms generated in blade template:

    @foreach($products as $product)

    <form id="product{{$product['id']}}" class="cartitem">
        <input type="hidden" class="cartitemid" name="cartitemid" value="{{$product['id']}}">
        <input type="text" class="count" name="count" value="{{$product['count']}}">
        <input type="hidden" name="cartid" value="{{$product['cartid']}}">
        {{ csrf_field() }}
    </form>

    @endforeach
<button id="refresh"  type="button" class="btn btn-danger" name="refresh" onClick="refresh(this);">Refresh</button> 

And that forms serialized and sent to controller via Jquery:

function refresh(btn){
    btn.blur();
    if ($('.cartitem').length) {
    $(".cartitem").each(function(){
        var data = $(this).serialize();
        $.ajax({
            url: '/cart/refresh',
            type: 'POST',
            data: data,
            success: function (response) {
              var str = JSON.stringify(response.cart, null, 2);
            console.log(response.id);
            console.log(response.count);
            console.log(str);
            }
        });
        location.reload();
});
}
}

Controller code:

    public function refresh(Request $request){  
    if (session()->has('cartitems')) {  
    $validatedData = $request->validate([
                   'cartitemid' => 'required|numeric',
                   'count' => 'required|numeric|between:1,255',
                   'cartid' => 'required|string|max:10',
                ]);
            $cartitems = $request->session()->get('cartitems');

                    $count = $validatedData['count'];
                    $id = $validatedData['cartitemid'];
                            foreach ($cartitems as $cartitem => $value){
                                if ($value['id'] == $id){
                                    $cartitems[$cartitem]['count'] = $count;

                                }
                            }
$response = array(
          'cart' => $cartitems,
          'count' => $count,
          'id' => $id,
      );

                  $request->session()->forget('cartitems');
                  $request->session()->put('cartitems', $cartitems);
                  return response()->json($response);
    }
    }

For some reason it's not working. Not saving array in some iterations. This also doesn't work with database or cookie driver.

UPDATE Code is working. I'm getting output in the console, like this:

1
1
1
[
  {
    "id": 1,
    "productid": "1",
    "count": "1",
    "price": 10001.2
  }
]

But in the session is still an old array.

2 Answers 2

1

The issue seems to be here

return response()->json($response);
              $request->session()->forget('cartitems');
              $request->session()->put('cartitems', $cartitems);

You run the return statement before the $request->session() so the code never go there.

Just set the return line at the end.

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

5 Comments

Yes, I missed this, but still can't save to session.
You have a condition if (session()->has('cartitems')), so I guess the cartitems session always exists before you call this method ? If you var_dump($request->session()->get('cartitems')) , just after the validation, what does it give to you ?
Yes, it exists. During testing, I also returned the original array to compare with the modified array.
So the array you push inside the session is well filled. If you check with another variable (test, 1) for example, it's don't work too ? I think you can also remove the forget line, as the put will replace the previous content
With one form everything works. But if two or more forms are generated, the result is not correct in the session. The processing of the second Ajax request, for some reason takes the original array instead of what was saved in the processing of the first one.
0

Well, I kinda solved my question. Very simple just adding in ajax request.

async: false

Comments

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.