Laravel 8 session not adding last product ids in array

Viewed 57

I am developing Cart system in Laravel 8 where I store product ids in Laravel session. So when customer add the product in cart, I check if session exists. If session exists, I get session in variable and add new product id in variable using array_push() method, then add the new variable in session.

But somehow when I tried to get session using Session::get() method, it only gives the first value from array.

Here is same code as I use for adding product id as $time variable.

$time = time();
if (\Session::has('cartitems')) {
    $cartitems = \Session::get('cartitems');
    \Session::forget('cartitems');
    array_push($cartitems, $time);
} else {
    $cartitems = [$time];
}

\Session::put('cartitems', $cartitems);
dd(\Session::get('cartitems'));

Using above code, whenever I call this route, $time should be added to session, but it is not adding, only last $time is added in Session. Same is happening in my Product cart, only last product is returning in my session.

Please help me. Thanks in advance.

0 Answers
Related