6

How can I check customer is logged in or not? If customer is not logged in then how to redirect him to the login page?

I want to do this from .phtml file. So please help me as per that.

8

If you want to do it directly from .phtml file use following code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('\Magento\Customer\Model\Session');
$urlInterface = $objectManager->get('\Magento\Framework\UrlInterface');

if(!$customerSession->isLoggedIn()) {
    $customerSession->setAfterAuthUrl($urlInterface->getCurrentUrl());
    $customerSession->authenticate();
}

Then after login you will be automatically redirected to current view.

But using Object Manager isn't good practice. You should use dependency injection whenever possible.

  • 3
    Direct instances of Object Manager are not best practice: magento.stackexchange.com/a/117101/1956 – ryanF Jun 13 '16 at 8:56
  • Still, Magento core team uses it in few models. The question was how to do it directly from .phtml file, and this is the answer :) – Bartłomiej Szubert Jun 13 '16 at 9:08
  • Szubert ... fair enough...just good to note, I suppose. – ryanF Jun 13 '16 at 9:11
  • Why it is going to infinite redirect loop – Naveenbos Dec 16 '16 at 8:26
8

@Krupali, if you're adamant about your code being implemented in a template, then @Bartlomiej Szubert's example is the better choice. Generally, it's best practice to hide away those implementation details from your template and abstract the logic away to something else (block or helper).

Here's an example of a helper implementation:

<?php

namespace Ryan\CustomerRedirect\Helper;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\UrlInterface;

class Customer extends AbstractHelper
{
    /**
     * @var Session
     */
    private $customerSession;
    /**
     * @var UrlInterface
     */
    private $urlInterface;

    public function __construct(
        Context $context,
        Session $customerSession,
    )
    {
        parent::__construct($context);
        $this->customerSession = $customerSession;
        $this->urlInterface = $context->getUrlBuilder();
    }

    public function redirectIfNotLoggedIn()
    {
        if (!$this->customerSession->isLoggedIn()) {
            $this->customerSession->setAfterAuthUrl($this->urlInterface->getCurrentUrl());
            $this->customerSession->authenticate();
        }
    }
}

Then in your template you can use something like this:

$this->helper('Ryan\CustomerRedirect\Helper\Customer')->redirectIfNotLoggedIn()

*namespace shown is an example

This way your code can be reused elsewhere...and if you decide to change the implementation logic of how you're checking if someone is logged in, you don't have to change your template(s).

  • Oh yes. This is very useful to me. – Krupali Jun 10 '16 at 11:55
  • 1
    @Krupali, I'm glad that this is helpful. You know, you can show that something is helpful by upvoting it :D – ryanF Jun 10 '16 at 15:57
  • helper in template actually is also using OM, but just nicely hidden :) – Bartosz Kubicki Dec 23 '16 at 7:30
0
Find the below working code from core file to redirect other page in controller.

<?php

namespace Vendorname\Yourmodulename\Controller\Contact;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Customer;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $customerSession;

    protected $customers;

    public function __construct(
        Context $context,
        Session $customerSession,
        Customer $customers
    )
    {
        parent::__construct($context);
        $this->customerSession = $customerSession;
        $this->customers = $customers;       
    }

    public function execute()
    {   
        if ($this->customerSession->isLoggedIn()) {

            //Get customer by customerID.
            $customerId = $this->customerSession->getCustomerData()->getId();
            $customer = $this->customers->load($customerId);
            if($customer->getUserRole() != '' && $customer->getUserRole() == 'admin')
            { 
                $this->_view->loadLayout();
                $this->_view->getLayout()->initMessages();
                $this->_view->renderLayout();            
            }
        }
        else{

            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('customer/account/login/');
            return $resultRedirect;        
        } 
    }
}   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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