I am just trying to get the customer session in my custom controller class and it always returns NULL.

What is wrong with Magento? It doesn't work as expected, I am spending days not minutes for a small changes...

Here is my custom controller class.

class Referral extends \Magento\Customer\Controller\AbstractAccount {

    protected $customerRepository;

    protected $dataObjectHelper;
    protected $session;
    protected $resultPageFactory;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        PageFactory $resultPageFactory,
        CustomerRepositoryInterface $customerRepository,
        DataObjectHelper $dataObjectHelper
    ) {
        $this->session            = $customerSession;
        $this->resultPageFactory  = $resultPageFactory;
        $this->customerRepository = $customerRepository;
        $this->dataObjectHelper   = $dataObjectHelper;
        parent::__construct( $context );

    public function execute() {
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()->getBlock( 'customer_account_dashboard_referral_edit' );
        if ( $block ) {
            $block->setRefererUrl( $this->_redirect->getRefererUrl() );

        $data = $this->session->getCustomerFormData(true);
        $customerId = $this->session->getCustomerId();

        $customerDataObject = $this->customerRepository->getById( $customerId );
        if ( ! empty( $data ) ) {
        $resultPage->getConfig()->getTitle()->set( __( 'Referral Settings' ) );

        return $resultPage;

In that case it returns NULL, I have found only one way to get real id

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

$customerSession = $objectManager->create("Magento\Customer\Model\Session");

In this case it works, and I can get customer id, but why??? What is the purpose of all these dependency injections and other features, it even doesn't work in a simple case...

Please explain what is wrong ?

1 Answer 1


I think you need do it :

PS: "purpose of all these dependency injections" use Factory ."

Example :

protected $sessionFactory;
public function __construct(
        \Magento\Customer\Model\SessionFactory $sessionFactory,
    ) {
        $this->sessionFactory = $sessionFactory;

    public function execute() {

        $sessionModel = $this->sessionFactory->create();
        $customerId = $sessionModel->getCustomer()->getId();
  • Thank you fro the answer, $this->session->getCustomer()->getId(); doesn't work either. The code with Session Factory works well, really disappointed by this Magento Jun 30, 2018 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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