How to Check if Customer is Logged in or Not in magento2 - magento source24


Hello magento friends todays in this blog post im share with you to How to Check if Customer is Logged in or Not in magento2. In Magento 2, you can check if a customer is logged in or not using both PHP code and template files. Here's how you can do it:


➤ Method 1: Using PHP code in a Controller, Block, or Model:

You can use the \Magento\Customer\Model\Session class to check if a customer is logged in or not. Here's an example of how to use it in a controller, block, or model:


How to Check if Customer is Logged in or Not in magento2 - magento source24


<?php

use Magento\Framework\App\Action\Action;

use Magento\Framework\App\Action\Context;

use Magento\Customer\Model\Session;


class MyController extends Action

{

    protected $customerSession;

    public function __construct(

        Context $context,

        Session $customerSession

    ) {

        parent::__construct($context);

        $this->customerSession = $customerSession;

    }

    public function execute()

    {

        if ($this->customerSession->isLoggedIn()) {

            // Customer is logged in

            // Your code here

        } else {

            // Customer is not logged in

            // Your code here

        }

    }

}

?>


➤ Method 2: Using template (.phtml) files:

You can also check customer login status directly in your template (.phtml) files using the following code:


How to Check if Customer is Logged in or Not in magento2 - magento source24


<?php

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

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


if ($customerSession->isLoggedIn()) {

    // Customer is logged in

    // Your HTML and PHP code here

} else {

    // Customer is not logged in

    // Your HTML and PHP code here

}

?>


Please note that using the ObjectManager directly, as shown in the second method, is not recommended for production code due to potential issues with dependency injection and best practices. It's better to use the first method with dependency injection.

Remember to customize the code according to your specific requirements and the context in which you are checking for customer login status.




Deepak Kumar Bind

Success is peace of mind, which is a direct result of self-satisfaction in knowing you made the effort to become the best of which you are capable.

Post a Comment

If you liked this post please do not forget to leave a comment. Thanks

Previous Post Next Post