Tag Archives: Magento 2 Tutorials

Magento 2 Collection get last Item


Magento 2 Collection get last Item: There are many ways to get last item from Magento collection. Here in this article we are going to explain one of the method to get last item from collection using order by and setPageSize.


Magento 2 Collection get last Item Example

You can add order by desc and setPageSize to get the last item from the collection. Here is an example to get last item-

Magento 2 Collection get last Item Example:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();   
$firstItem = $objectManager->create('Mypackage\MyModule\Model\MyData')
                    ->getCollection()
                    ->setOrder('id DESC')
                    ->setPageSize('1');

The above example will give last item so on the same way you can get the first item by just adding ->setOrder(‘id ASC’)

Magento 2 Get Product Attribute


Magento 2 Get Product Attribute Value By Code It is very simple to get the product’s custom attribute value by attribute code. You also get easily get the attribute options detail. Here in this tutorial we are going to explain how to get the product’s custom attribute in Magento2.


Magento 2 Get Product Attribute | Custom Attribute | Options Example

Let us go one by one to get the product attribute Details-

Get Product Attribute Value By Code

You can get the product custom attribute value by code simply as below-

Magento 2 Get Product Custom Attribute Example:

$productId = 654;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
   $myCustomAttrVal = $product->getData('my_custom_attribute');

The above Example will give you custom atribute value by code.

Get Product Attribute Options Value

Get Product Custom Attribute Options Value In Magento2 Example:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');
$options = $attribute->getSource()->getAllOptions();

$optionsExists = array();

foreach($options as $option) {
    $optionsExists[] = $option['label'];
}
print_r($optionsExists);

The above example will give you all options available for attribute.

Get Product Attribute Labels

Get Product Custom Attribute Options Label In Magento2 Example:

$productId = 100;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId);
$product = $this->objectFactory->get('Magento\Catalog\Model\Product')->load($product_id);

$attributes = $product->getAttributes();
$lables = array();
foreach ($attributes as $attribute) {

$lables[]= $attribute->getStoreLabel();

}
print_r($labels);

The above example will give you options label from product object.