Laravel, add to cart ajax(session issue)


#1

Hi, guys when I try to add item to EMPTY(empty session) cart asynchronously it doesn’t work. But if I refresh the page the item appears in cart and from there I can add items asynchronously. I’m pretty sure the problem is, that session[basket] variable isn’t initialised for the first request. but how do I resolve it? What am I missing?
controller code
[php]
public function addToBasket(Request $request, $id)
{
$product = Product::find($id);
//check if basket exists in session, if it does get it
$previousBasket = Session::has(‘basket’) ? Session::get(‘basket’) : null;

    $newBasket = new Basket($previousBasket);
    $newBasket->addProduct($product, $product->id);

    Session::put('basket', $newBasket);
    return response()->json(['added' => Session::get('basket')->quantity], 200);
}

[/php]

ajax:

var id = $(this).data('id');
  var url = "/product/add-to-basket/"

  $.ajax({
    type: "GET",
    url: url+id,
    dataType: "json",
    data: { id: id },

    success: function(data) {
      if(data) {
        $('#cart-counter').html(data['added']);
        console.log(data);
      }