CakePHP 3 : Trying to get property of non-object

点点圈 提交于 2019-12-12 03:37:15

问题


I'm working on CakePHP 3.2 and in login() action, want to allow login to only those whose status is verified = 1

public function login()
    {
      if ($this->request->is('post') || $this->request->query('provider')) {
        $user = $this->Auth->identify();
        if ($user) {
          if ($user->verified != 1) {   // LINE 6
            $this->Flash->error(__('You have not yet verified your account. Please check your email to verify your account before login'), [
              'params' => [
                'userId' => $user->id,   // LINE 9
              ],
              ['escape' => false]
            ]);
            $this->redirect(['action' => 'login']);
          }
          $this->Auth->setUser($user);
          $this->_setCookie();
          $this->Flash->success('Login Success');
          return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
      }
    }

But this gives error as

Notice (8): Trying to get property of non-object [APP/Controller/UsersController.php, line 6]
Notice (8): Trying to get property of non-object [APP/Controller/UsersController.php, line 9]
Warning (2): Cannot modify header information - headers already sent by (output started at /var/www/html/argoSystems/projects/project_01/site/vendor/cakephp/cakephp/src/Error/Debugger.php:746) [CORE/src/Network/Session.php, line 572]
Warning (2): session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent [CORE/src/Network/Session.php, line 576]

NOTE : line number has been changed to meet code snippets


回答1:


Solved my problem. This is my updated login() method.

public function login()
    {
      if ($this->request->is('post') || $this->request->query('provider')) {
        $user = $this->Auth->identify();
        if ($user) {
          $this->Auth->setUser($user);
          if ($this->Auth->user('verified') != 1) { 
            $this->Flash->error(__('You have not yet verified your account. Please check your email to verify your account before login'), [
              'params' => [
                'userId' => $this->Auth->user('id'),
              ],
              ['escape' => false]
            ]);
            return $this->redirect($this->Auth->logout());
          }
          $this->_setCookie();
          $this->Flash->success('Login Success');
          return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
      }
    }



回答2:


you could have solved this easily! Change line 6 for example from

if ($user->verified != 1) { // LINE 6

to

$user["verified"] != 1) { // LINE 6



来源:https://stackoverflow.com/questions/38152791/cakephp-3-trying-to-get-property-of-non-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!