Magento 2 PHP – Get Product Attribute Value for Shipping Methods

magento2PHPshippingshipping-methods

I have made a shipping Model in Magento 2 . Inside the collectRates function. I am getting all items in the cart and looping through them.

I can set the price based on the product title. But I can't get the value of the attribute this product has for example "shipping_code".

$products = $request->getAllItems();

foreach($products as $product){
   $productName = $product->getName();
}

I have tried everything.

$attributeValue = $product->getData('shipping_code');
$attributeValue = $product->getResource()->getAttribute('shipping_code');
$attributeValue = $product->getAttribute('shipping_code');

What am I doing wrong?

Magento/App/Code/module_folder/custom_shipping/Model/Carrier/custom_shipping.php

public function collectRates(RateRequest $request){

    $products = $request->getAllItems();
    foreach($products as $product)
    {
       $productName = $product->getName();
       $attributeValue = $product->getData('shipping_code');
    }



     $shippingPrice = "100";

    if ($productName == "test") {
        $shippingPrice = "200";
    }

    if ($attributeValue == "A") {
        $shippingPrice = "300";
    }

    $method->setPrice($shippingPrice);
    $result->append($method);

    return $result;
}

Best Answer

foreach($products as $product)
{
   $productName = $product->getName();

   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
   $shippingCode = $product->getData('shipping_code');
}

If somone gives answer without objectManager then it will be better.