Удалить элемент из сессии - PullRequest
0 голосов
/ 02 мая 2019

у меня есть 2 функции для моей корзины покупок, первая общая сумма возврата и общее количество товаров:

public function GetCartTotal(Request $request)
{
    if (!Session::has('cart')) {
        return Response::json([null]);
    }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    return Response::json([
        'totalPrice' => $cart->totalPrice, 
        'totalQty' => $cart->totalQty]
    );
}

public function GetCartItems()
{
    if (!Session::has('cart')) {
        return Response::json(['items' => null]);
    }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    return Response::json(['items' => $cart->items]);
}

эти две функции возвращают эти два массива:

{
    totalPrice: 320750000,
    totalQty: 9
}

и

{  
   items:{  
      1:{  
         id:1,
         qty:5,
         price:750000,
         item:{  
            id:1,
            name:"Product title 1",
            desc:null,
            price:"150000",
            barcode:"1556717299",
            Image:"1556717299.jpg",
            count:"25",
            created_at:"2019-05-01 17:58:19",
            updated_at:"2019-05-01 17:58:19"
         }
      },
      2:{  
         id:2,
         qty:4,
         price:320000000,
         item:{  
            id:2,
            name:"Product title 2",
            desc:null,
            price:"80000000",
            barcode:"1556729461",
            Image:"1556729461.jpg",
            count:"52",
            created_at:"2019-05-01 21:21:01",
            updated_at:"2019-05-01 21:21:01"
         }
      }
   }
}

я могу уничтожить всю сессию корзины с помощью этой функции:

public function RemoveAllCartItems(){
    Session::forget('cart');
}

как я могу удалить определенные элементы корзины? Я использую этот метод, и он работает. Но он не меняет totalprice и total qty:

public function RemoveCartItem(Request $request, $id){
    $cart = Session::get('cart');
    unset($cart->items[$id]);
}

1 Ответ

1 голос
/ 02 мая 2019

Вы можете достичь этого с помощью pulling -> updating -> putting

$cart = Session::pull('cart'); // Retrieve and delete an item
unset($cart->items[$id]);
// Add any additional logic that updates $cart (eg: updating qty and total price)
Session::put('cart', $cart);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...