Search code examples
sessioncakephpcakephp-2.3

Refresh User Session Array After Editing Information CAKEPHP


I would like to know how I can make the array (Auth.User) reload after a user has updated their information.

At the moment this wont happen until the user logs out and then back in as that's when it loads the array (Auth.User).

So far I have tried a few solutions such as.

I have also tried adding $user = $this->User->field('name', array('User.id' => $this->Session->read('Auth.User.id'))); $this->Session->write('Auth.User', $user); into the app controller.

But none have been successful.

Thanks


Solution

  • You're just about there. Remember that the returned array $user contains a 'User' key, such as:

    array(
      'User' => array(
        'id' => 1
      )
    )
    

    So saving it to the session under Auth.User would actually save the session array like so:

    array(
      'Auth' => array(
        'User' => array(
          'User' => array(
            'id' => 1
          )
        )
      )
    )
    

    Instead, save it into the Auth key and you can continue accessing it like normal:

    $user = $this->User->field('name', array(
      'User.id' => $this->Session->read('Auth.User.id')
    )); 
    $this->Session->write('Auth', $user);
    

    Now that the session keys are cleared up, there's a much easier and quicker way of re-logging in the user, as mark says in the comments: use $this->Auth->login().

    $user = $this->User->field('name', array(
      'User.id' => $this->Session->read('Auth.User.id')
    )); 
    $this->Auth->login($user);