0

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',
                ]
            );

my document in mongo

1 Answer 1

1

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
            }
            
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.