CakePHP Auth Model Update User on Model Edit

Ok, so I’m in the mood to write a little bit. I finished my grad school homework a little early, so I’d like to talk about CakePHP. Specifically, updating your user model session data when the user model is edited.  Here is the scenario:

  • Your are using CakePHP’s wonderful Auth Component.
  • After a successful login, you have auth model data available to you via $this->Auth->user(’key’);
  • It just so happens that this model data is stored in a session, in a format something like the following:
Array
(
    [Auth] => Array
    (
        [Model] => Array
        (
            [id] => 1
            [first_name] => Jason
            [last_name] => Leveille
        )
    )
)
  • You use this data
  • When you update your user model, you want this data updated as well

If you’re anything like I am, you make use of this data to display information to your authenticated user. For example, in your controller you might set a firstName variable for use in a welcome message.

$firstName = $this->Auth->user('first_name');
$this->set(compact('firstName'));

It’s very likely that you have provided an edit action in your auth userModel controller. It’s also likely that you have provided the user with the ability to modify their first name. In our welcome message, we are pulling our first name data from a session. If we want this data to be accurate, than the change to our user first name in the action will also need will not be reflected in this auth session. The solution of course is to merge $this->data['$this-Auth->userModel] with our Auth.Model session.

//update the auth userModel data
$authUpdated = Set::merge(
    $this->Session->read(
        sprintf('Auth.%s', $this->Auth->userModel)
    ),
    $this->data[$this->Auth->userModel]
);
$this->Session->write(
    sprintf('Auth.%s', $this->Auth->userModel),
    $authUpdated
);

Again, this code would be part of your user model edit action, and would be included after a successful save operation.

Tags: ,

2 Responses to “CakePHP Auth Model Update User on Model Edit”

  1. etipaced says:

    Thanks Jason, this is exactly what I was trying to do. I didn’t know about Set::merge() but it’s a very helpful function. Just to help the Google bot, here’s what I typed into Google to find this article:

    “cakephp update auth user session”

  2. leveille says:

    No problem etipaced. I’m glad you found this useful. There is also this thread which others may or may not find useful:

    http://n2.nabble.com/$this-%3EAuth-%3Euser-not-refreshing-after-edit-td526651.html

Leave a Reply