1
votes

I'm trying to make a shopping cart like function using Laravel's session and in the front end side, I'm using Ajax to instruct the back end to create the session.

//add to cart
$(document).on('click','.add-to-cart',function(e){
    e.preventDefault();
    var dis = $(this);
    $.ajax({
        url : site_link+'/product/add-to-cart',
        data : { item_id : dis.attr("data-id") },
        type : 'post',
        dataType : 'json',
        success: function(e){
            console.log(e);
        }
    })
});

and then check the cart

//check the cart
$(document).on('click','.check-the-cart',function(e){
    e.preventDefault();
    var dis = $(this);
    $.ajax({
        url : site_link+'/product/check-the-cart',
        data : { item_id : dis.attr("data-id") },
        type : 'post',
        dataType : 'json',
        success: function(e){
            console.log(e);
        }
    })
});

and in the controller, add a cart to the session

public function add_to_cart(Request $request){
    $product = collect([1,2,3,4]);
    Session::put('cart', $product);

    dd(var_dump(session::get('cart')));
}

and the dump returns the expected data and then the second post request, check the 'cart' sessions contents.

public function add_to_wishlist(Request $request){
    dd(var_dump(session::get('cart')));
}

but it returns 'NULL' which I'm not expecting to be null as I set the 'cart' to the session in the first 'POST' request. Any ideas, help please?

1

1 Answers

1
votes

Try change

Session::put('cart', $product);

to

Session::push('cart', $product);

and to get the session value

Session::get('cart')[0];