I'm using this code in a block to get a collection of orders in Magento 2:

$orders = $this->orderCollectionFactory->create()
            ->addFieldToFilter('customer_id', $customerId);

And so far it works great, I can loop through the orders and output the order data in the frontend.

However, I want to remove some orders from this collection, for example order with ID of 21. I tried to use removeItemByKey() to accomplish this:

foreach ($orders as $order) {
    if($order->getId() == 21) $orders->removeItemByKey($order->getId());

But this doesn't work and the order with ID 21 remains in the order collection.

I've also tried this instead:

foreach ($orders as $order) {
    if($order->getId() == 21) unset($orders->{$order->getId()});

Same result, order 21 still in the collection.

Why doesn't this work and how can I remove stuff from the order collection?


1 Answer 1


If you look at the function itself,

    File: lib/internal/Magento/Framework/Data/Collection.php
    Line: 454-466
     * Remove item from collection by item key
     * @param mixed $key
     * @return $this
    public function removeItemByKey($key)
        if (isset($this->_items[$key])) {
        return $this;

you can see that it removes by array key. My guess here is that the array key is not necessarily equal to $order->getId(). You could rewrite your loop:

foreach ($orders as $key => $order) {
     if($order->getId() == 21) $orders->removeItemByKey($key);

This should do the trick.

A more efficient way would be to pre filter your collection with NOT IN like:

         array('nin' => $arrayWithOrderIds)

Hope I could help.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.