Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting associated models with $this->Auth in Cakephp

I am using CakePHP 2.0's integrated Auth component. I have the following tables :

  • Users
  • Groups
  • Profiles

My model relations are as follows:

User belongsTo Group
User hasMany Profiles

While logged in to the site, I noticed the Auth session contains only User table information, but I need the information of Groups and Profiles tables too for the logged in user.

Is there any way to do that with the Auth component?

like image 711
AnNaMaLaI Avatar asked Mar 20 '12 11:03

AnNaMaLaI


1 Answers

There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself.

The only way to do this is to add to the session when the user logs in:

function login() {
    if ($this->Auth->login($this->data)) {
        $this->User->id = $this->Auth->user('id');
        $this->User->contain(array('Profile', 'Group'));
        $this->Session->write('User', $this->User->read());
    }
}

Then in your beforeFilter() in your AppController, save a var for the controllers to get to:

function beforeFilter() {
    $this->activeUser = $this->Session->read('User');
}

// and allow the views to have access to user data
function beforeRender() {
    $this->set('activeUser', $this->activeUser);
}

Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session.

like image 159
jeremyharris Avatar answered Sep 28 '22 18:09

jeremyharris