How can i check whether user is logged in or not in magento 2.0
To check if customer is loged in or not you can call Magento\Customer\Model\Session::isLoggedIn() method.
If you want to do that properly in *.phtml files you should use helper inside the template. Object manager is not preferred way to call models inside template files. So I am not recommending to follow this post There isn't core helper that can be reused so you need to create new one.
<?php
namespace YourCompany\ModuleName\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Customer\Model\Session $customerSession
) {
$this->customerSession = $customerSession;
parent::__construct($context);
}
public function isLoggedIn()
{
return $this->customerSession->isLoggedIn();
}
}
Then in your *.phtml file you can call your helper and call isLoggedIn method like this:
<?php $helper = $this->helper('YourCompany\ModuleName\Helper\Data'); ?>
<?php if($helper->isLoggedIn()) : ?>
logged in
<?php else : ?>
not logged in
<?php endif; ?>
This is for only Magento 2.0, add this in phtml
file:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
Check via following:
if($customerSession->isLoggedIn()){
// your code
}
If you want to get user logged in at template level phtml, you can call :
<?php $_loggedin = $this->helper('Magento\Checkout\Helper\Cart')->getCart()->getCustomerSession()->isLoggedIn(); ?>