cakephp 2.0 how to update auth data?

后端 未结 7 1477
别那么骄傲
别那么骄傲 2021-02-01 08:12

when I update data in the User model, the Auth data is not updated.

How can I \"refresh\" the data which is returned by $this->Auth->user() when I am updating user model

7条回答
  •  不要未来只要你来
    2021-02-01 08:47

    evert0ns answer is right. But you should use AuthComponent::login(), because the data is saved within the AuthComponent as well and is not fetched from the session every time.

    I had the problem just a couple of days ago.

    // AppController.php
    /**
     * Renews current user data, e.g. in case of an email address change while being logged in.
     *
     * @param array $newUserData
     * @return void
     */
        protected function renewUserSession($newUserData){
                if(!isset($newUserData) || empty($newUserData)){
                        return;
                }
    
                // We need to fetch the current user data so custom indexes are copied
                $currentUserData = $this->Auth->user();
                if(!isset($currentUserData) || empty($currentUserData)){
                        return;
                }
    
                // Merge old with new data
                $newUserData = array_merge($currentUserData, $newUserData);
    
                // Login with new data
                $this->Auth->login($newUserData);
        }
    

    Source: my paste

    Put this in your AppController. The method is specialized to merge the current and the new user data to keep existing custom indexes that you may have provided. I needed this, but you can leave it out though. Give the updated user data as a parameter to the method. Not in model find form. E.g.:

    $data = array(
        'User' => array(
            'username' => 'bla',
            'passwort' => 'fu',
            'email' => 'hu@bar.com'
        )
    );
    
    // Wrong
    $this->renewUserSession($data);
    
    // Right
    $this->renewUserSession($data['User']);
    

提交回复
热议问题