Fatal error: Call to a member function user() on boolean

两盒软妹~` 提交于 2019-12-23 05:40:58

问题


I have to use loggedIn user data in view therefore creating a variable AUTH_USER in AppController in beforeRender function.

82     public function beforeRender(Event $event)
83     {
84          if ($this->Auth->user('id')) {
85          $this->set('AUTH_USER', $this->Auth->user());
86          }
87          ...
88          ...
89     }

Whenever there is an error, instead of displaying actual error it shows following error without style formatting

Fatal error: Uncaught Error: Call to a member function user() on boolean in /path_to_app/src/Controller/AppController.php:84 
Stack trace: #0 /path_to_app/src/Controller/ErrorController.php(54): App\Controller\AppController->beforeRender(Object(Cake\Event\Event)) 
#1 /path_to_app/vendor/cakephp/cakephp/src/Event/EventManager.php(422): App\Controller\ErrorController->beforeRender(Object(Cake\Event\Event)) 
#2 /path_to_app/vendor/cakephp/cakephp/src/Event/EventManager.php(391): Cake\Event\EventManager->_callListener(Array, Object(Cake\Event\Event)) 
#3 /path_to_app/vendor/cakephp/cakephp/src/Event/EventDispatcherTrait.php(78): Cake\Event\EventManager->dispatch(Object(Cake\Event\Event)) 
#4 /path_to_app/vendor/cakephp/cakephp/src/Controller/ in /path_to_app/src/Controller/AppController.php on line 84

Removing line 84 - 86 displays actual error

Edit 2

code for Auth component load in AppController initialize()

I have written the following code to load the AUTH component.

$this->loadComponent('Auth', [
   'authenticate' => [
      'Form' => [
         'userModel' => 'Admins',
            'fields' => [
               'username' => 'email', 
               'password' => 'password'
             ]
         ]
      ],
      'loginAction' => [
         'controller' => 'Admins',
         'action' => 'index'
      ],
      'loginRedirect' => [
         'controller' => 'Admins',
         'action' => 'contentList'
       ],
      'authError' => 'Did you really think you are allowed to see that?',
      'logoutAction' => [
         'controller' => 'Pages',
         'action' => 'home'
       ]
]);

回答1:


I had the same error and if you add this line to beforeRender() it should work:

$this->loadComponent('Auth');

It could be that you are not properly initializing the component in the initialize() function.




回答2:


You haven't given a proper ID to the if statement to check. You have to send the logged in user's ID through the function's parameters and then check for that ID in the if statement.



来源:https://stackoverflow.com/questions/41409547/fatal-error-call-to-a-member-function-user-on-boolean

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