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 ?
              }

            }
1

This works perfectly

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

Just try below code

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

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

            }
  • 2
    it removes that product from database or not ? – Ashar Riaz Jan 23 at 10:48
  • Yes it will remove products from database if its a collection of product – Satish Gumudavelly Jan 23 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 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.