0

I create route, and controller for it. All works fine if i call route like so.

....

return $this->_pageFactory->create();

....

However when I want get user data from Magento\Customer\Model\Session inside controller i get error. I use $om to get data but i don`t know why it crash. I need user session for redirect to login form if user is not logged in.

...
 $om = $context->getObjectManager();
 $this->_customerSession = $om->get('Magento\Customer\Model\Session');
 $this->_resultFactory = $context->getResultFactory();
...

in execute

if ($this->_customerSession->isLoggedIn()) {
 return $this->_pageFactory->create();
}
$redirect = $this->_resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
$redirect->setUrl('/customer/account/create/');
return $redirect;

So question is how to redirect customer away from route if its not log in ?

asked Aug 3, 2021 at 9:00
3
  • Does this answer your question? How to check if customer is logged in or not? Commented Aug 3, 2021 at 9:20
  • Replace with $redirect->setUrl('customer/account/create/'); Commented Aug 3, 2021 at 10:13
  • redirect works i just don`t want to use objectManager in controller to create dependency. But when i add dependency to constructor it breaks. Commented Aug 9, 2021 at 7:37

1 Answer 1

1

Please use like below in your controller to get customer session.

<?php
/**
 *
 * Copyright © 2015 Zmagecommerce. All rights reserved.
 */
namespace Vendor\Module\Controller\Index;
class Custom extends \Magento\Framework\App\Action\Action 
{
 protected $_customerSession;
 
 protected $_customerUrl;
 public function __construct(
 \Magento\Framework\App\Action\Context $context,
 \Magento\Customer\Model\Session $customerSession,
 \Magento\Customer\Model\Url $customerUrl
 ) {
 $this->_customerSession = $customerSession;
 $this->_customerUrl = $customerUrl;
 parent::__construct($context);
 }
 public function isCustomerLogin()
 {
 return $this->_customerSession->isLoggedIn();
 }
 public function getCustomerLoginUrl() 
 { 
 return $this->_customerUrl->getLoginUrl();
 }
}
answered Aug 10, 2021 at 14:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.