2

How to remove any object from magento 2 collection. If we have collection of products and we want to delete product which is at first index . how to delete that product without deleting it from database?

$collection->addAttributeToSelect('*')->addFieldToFilter('attribute',$somevalue);

foreach ($collection as $key => &$value) {
              if($key == 1){
                //// how to unset this index in collection ?
              }

            }

3 Answers 3

2

This works perfectly

  $productCollection->removeItemByKey($product->getEntityId());
2

You can try below code for deleting it

foreach ($collection as $key => $brand) {
   if ($brand->getIsDisabled()) {
      $collection->removeItemByKey($key);
   }
}
-4

Just try below code

<?php 
$collection->addAttributeToSelect('*')->addFieldToFilter('attribute',$somevalue);

foreach ($collection as $key => $value) {
              if($key == 1){
               $value->delete(); //Just Use it.
              }

            }
3
  • 2
    it removes that product from database or not ?
    – Ashar Riaz
    Jan 23, 2019 at 10:48
  • Yes it will remove products from database if its a collection of product Jan 23, 2019 at 13:48
  • 2
    Actually i dont want to remove that product from database. I just want to drop it from collection.
    – Ashar Riaz
    Jan 23, 2019 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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