I want all products with name starts with character 'a'(case insensitive) . I am using the following code but it is not working

$i = 'a';
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
                   ->addAttributeToSelect(['name', 'price', 'image']) 
                   ->addAttributeToFilter('name', array('like'=>$i.'%'));
   echo count($productcollection );                                   
  • I am trying your code it's working fine. How you print collection? – Prince Patel Aug 31 '17 at 5:56
  • Just printing the collection count. – Jancy Abraham Aug 31 '17 at 6:09
  • Share your code to printing count of the collection which you used. – Prince Patel Aug 31 '17 at 6:16
  • please check my edited answer – Jancy Abraham Aug 31 '17 at 6:25

You should not use ('like' => '%a%') if you want results to start with a only because %a% makes search wildcard. You need to use 'a%'. If this isn't working in your case then, you should double check your table records or print SQL query to inspect.


The like filter isn't case-sensitive by default. If you want to make it so, see this answer by @raphael.


Try to use this code :

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
    $productcollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection')
           ->addAttributeToSelect(['name', 'price', 'image'])
           ->addAttributeToFilter('name', array('like' => 'a%'))
  • no,it is not working. If we add % in first ,then it is working ->addAttributeToFilter('name', array('like' => '%a%')) – Jancy Abraham Aug 31 '17 at 5:24
  • Okay sir... I update it... You can accept answer if it is correct. – Rohan Hapani Aug 31 '17 at 5:33
  • But I want the product name with starting letter 'a'. If I use the above code ,then it will return all items containing letter ' a' – Jancy Abraham Aug 31 '17 at 5:49
  • then %a is better option. try to fire query in sql table. If in table working then something going wrong. – Rohan Hapani Aug 31 '17 at 6:05

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.