0

Magento 2 saves data in a 'sales_order_tax' table per transaction. I need to get the tax code and tax percent from this table for each order; however I can't find methods to do so? $order->getTaxPercent() would be obvious, but this does not work.

I do not need or want the tax percentage at an item level; just the tax rate on an order based on shipping address.

2 Answers 2

1

In Magento 1 you would have done this with getFullTaxInfo() but since it is not available in Magento 2. You have to get tax at item level and iterate through those to get shipping items.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$taxItems = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\Tax\Item');
$orderTaxItems = $taxItems->getTaxItemsByOrderId('1'); // Your Order Id

if (is_array($orderTaxItems)) {
        foreach ($orderTaxItems as $item) {
            if ($item['taxable_item_type'] === 'shipping') {
                // Your Order Tax Item for Shipping
            }
        }
    }

For more reference in implementation please refer here. Hope it finds helpful to you.

0

Add this to your class where you need to retrieve the tax percent

private $taxCollectionFactory;

public function __construct(
.....
\Magento\Sales\Model\ResourceModel\Order\Tax\CollectionFactory $taxCollectionFactory,
...
) {
   ....
    $this->taxCollectionFactory = $taxCollectionFactory;
   ...
}

then you can get all the taxes and tax percents applied to the order like this: Assuming you have the $order object

$taxes = $this->taxCollectionFactory->create()->loadByOrder($order);

Now you can loop through the taxes and get all the percentages:

foreach ($taxes as $tax) {
   //do something with $tax->getPercent();
   //or $tax->getAmount();
}

You will always gets a collection because you can have multiple taxes applied to the order. If you are sure you only have one tax configured you can use $taxes->getFirstItem() in the code above and get the first element of the collection.

2
  • the method getByOrder() doesn't exist in Magento 2.3 Commented May 6, 2020 at 12:48
  • yeah, it's called loadByOrder sorry about that
    – Marius
    Commented May 6, 2020 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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