Reputation: 237
I am trying to remove an element in a nested array inside mongo in my laravel project. I tried many ways to do it but after checking nothing was changed in my array.
I tried multiple way with no luck
$removeItem = Carts::query()
->where('userUID', '=', $user->UID)
->where('cart', '=', 'default')
->where('items.item', '=', $item['item'])
->pull(
'items',
'items.$',
);
i tried this as well:
$removeItem = Carts::query()
->where('userUID', '=', $user->UID)
->where('cart', '=', 'default')
->where('items.item', '=', $item['item'])
->pull(
'items',
[
'item' => 'items.$.item',
'location' => 'items.$.location',
'price' => 'items.$.price',
'quantity' => 'items.$.quantity',
'status' => 'items.$.status',
'added_on' => 'items.$.added_on',
'updated_on' => 'items.$.updated_on',
'deleted_on' => 'items.$.deleted_on',
]
);
Upvotes: 0
Views: 936
Reputation: 237
I was able to fix it by adding the variable name to it and also because i am removing an index, going in reverse like so:
for ($i=count($userCartBis['items']) - 1; $i >= 0; $i--) {
//for now remove each element from the cart and put it in the orders section, if it's active
if ($userCartBis['items'][$i]['status'] == 'active') {
//this one we can process
//add it to the orders table
$updateOrder = $order
->push(
'products',
[
'location' => $userCartBis['items'][$i]['location'],
'quantity' => $userCartBis['items'][$i]['quantity'],
'price' => $userCartBis['items'][$i]['price'],
'product' => $userCartBis['items'][$i]['item'],
]
);
//remove it from the cart table
$removeItem = $userCart
->pull(
'items',
$userCartBis['items'][$i],
);
} else if ($userCartBis['items'][$i]['status'] == 'deleted') {
//it is already deleted
//do nothing for now
}
}
Upvotes: 1