You can fetch a list of all the active shipping methods carrier code, the title, amount from the current quote id using Magento 2.
When you are working with checkout customization or you required to get all the active shipping methods for the current quote, You can get all the active shipping methods from the quote.
You can use Magento\Quote\Api\ShippingMethodManagementInterface interface for getting shipping methods.
Check the below code snippets for fetch active shipping methods carrier code, title
<?php namespace Path\To\Class; use Exception; use Magento\Framework\Exception\StateException; use Magento\Framework\Exception\LocalizedException; use Magento\Quote\Api\ShippingMethodManagementInterface; class ShippingCarrierCode { /** * @var ShippingMethodManagementInterface */ private $shippingMethodManagement; public function __construct( ShippingMethodManagementInterface $shippingMethodManagement ) { $this->shippingMethodManagement = $shippingMethodManagement; } /** * get shipping method code * * @return string[] * @throws LocalizedException */ public function getShippingFromQuote() { $quoteId = 1; try { $getShippingMethods = $this->shippingMethodManagement->getList($quoteId); $methodCodes = []; foreach ($getShippingMethods as $method) { $methodCodes[] = $method->getMethodTitle() . '=>' . $method->getAmount(); } } catch (StateException $stateException) { throw new LocalizedException(__($stateException->getMessage())); } catch (Exception $exception) { throw new LocalizedException(__($exception->getMessage())); } return $methodCodes; }
$this->getShippingFromQuote() return current selected shipping method data.
You can fetch getAmount(), getCarrierTitle(), getMethodTitle() related data also.
If Your Quote id is not active, Error will be thrown like,
No such entity with cartId = 1
If you don’t select Shipping method from shipping list, Error will be,
The shipping address is missing. Set the address and try again.
Output for Flat rate shipping method as selected for the current quote:
Array
(
[0] => flatrate => 5.00
)
If your shipping carrier contains more than one shipping method, they will return all the active methods as output.