In Magento 2, You can redirect to any link or forcefully redirect to any link by Magento\Framework\Controller\Result\RedirectFactory object.
Using setUrl($url) -> You need to pass link as parameter for redirect
Using setPath($path) -> You need to pass path(action URL) as parameter
public function __construct( \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory ) { $this->resultRedirectFactory = $resultRedirectFactory; }
1. Using a direct path, you need to pass the action URL in a setPath() method.
Redirect to the cart page, Pass action path as checkout/cart,
Redirect to contact page, the parameter is `contact ` only
To Redirect to a login page, a parameter is customer/account/login
$resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('checkout/cart'); return $resultRedirect;
2. Pass Query string, Add Second Argument as a Query string array to use custom query string in URL.
$argument = ['id' => $getId, '_current' => true]; $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('checkout/cart',$argument); return $resultRedirect;
You can redirect to any link by direct URL using below way,
3. Full URL redirect with Magento,
$resultRedirect = $this->resultRedirectFactory->create(); $url = 'http://127.0.0.1/magento2/checkout/cart'; $resultRedirect->setUrl($url); return $resultRedirect;
You need to pass the full URL for a redirect to a specific link in Magento 2 in the setUrl method.