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.
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.
@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).
There is a simple di.xml
pref for this:
<type name="Vendor\Module\Your\Controller">
<plugin name="auth-redirect-plugin" type="Magento\Customer\Controller\Plugin\Account"/>
</type>
Don't need to write code when Magento already wrote it