Magento 2 – Redirect to External URL from Controller

controllersmagento2magento2.2redirect

I want to redirect to a external URL in my controller but not in the execute() function.

This code works fine and the result is a redirect to google:

public function execute()
{
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($this->session->isLoggedIn()) {
        $resultRedirect->setUrl('https://www.google.co.uk');
        return $resultRedirect;
    }
 )

However, this code is not working:

public function execute()
{
    $this->testRedirect();
 )

public function testRedirect(){
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($this->session->isLoggedIn()) {
        $resultRedirect->setUrl('https://www.google.co.uk');
        return $resultRedirect;
    }
}

This code doesn't redirect and leave the page blank.

What am I doing wrong?

Best Answer

As per the code you are calling another function from execute i.e testRedirect() which is returning object resultRedirect, but with the object you are not doing anything in execute function. That is why it is showing blank page.

Try this if it works:

public function execute()
{
    return $this->testRedirect();
 )