17

Is there a way of accessing the current session in the AppModel class?
I want to save the ID of the currently logged in user to almost every INSERT/UPDATE action.

powtac
  • 37,821
  • 25
  • 107
  • 164

4 Answers4

17

Found a working solution for CakePHP 2 here: Reading a session variable inside a behavior in cakephp 2

This is my AppModel:

<?php
class AppModel extends Model {

    public function beforeSave() {
        parent::beforeSave();

        if (isset($this->_schema['user_id'])) {

            // INSERT
            if (!strlen($this->id)) {

                App::uses('CakeSession', 'Model/Datasource');
                $user_id = CakeSession::read('Auth.User.id');

                $this->data[$this->alias]['user_id'] = $user_id;

            // UPDATE, don't change the user_id of the original creator.
            } else {
                unset($this->data[$this->alias]['user_id']);
            }
        }
        return true;
    } 
}
Community
  • 1
  • 1
powtac
  • 37,821
  • 25
  • 107
  • 164
  • 1
    As per my 3rd option, just because you can doesn't mean you should. – Scott Harwell Jan 05 '12 at 00:02
  • 1
    I simply went from `$this->Session->write('Auth.User.jwt', $jwt);` to `CakeSession::write('Auth.User.jwt', $jwt);` to get my code working from Controller to Model. – Vael Victus Mar 02 '21 at 19:02
10

In CakePHP 2.x you can use AuthComponent statically and get the logged in user's ID in the model like this:

$userId = AuthComponent::user('id');
Will
  • 1,801
  • 3
  • 26
  • 41
9

If you are calling saves from a controller, you could just include the session data in the data that you assign to your model before the save:

$data['ModelName']['session_id'] = $this->Session->id;
$this->ModelName->save($data);

Or you could create a variable in your model and store the ID there for use later:

<?php
//in model
class MyModel extends AppModel{
   public $session_id;
}


//in controller
$this->MyModel->session_id = $this->Session->id;
?>

If you must use the component in your model, then you may be able to load it. I'm not sure if this will work though. This is not good practice and you should probably consider doing it a different way.

<?php

App::uses('CakeSession', 'Model/Datasource');

class MyModel extends AppModel{
   public function beforeSave(){
       $this->data['session_id'] = $this->Session->id;

       return true;
   }
}

?>
Scott Harwell
  • 7,327
  • 2
  • 26
  • 41
3

For 3.6 and above, to access current Session from Table class use Cake\Http\Session

use Cake\Http\Session;

class UsersTable extends Table
{
    /**
     * Get user from session
     *
     * @return object
     */
    public function getUser()
    {
        $id = (new Session())->read('Auth.User.id');
        $user = TableRegistry::getTableLocator()
         ->get('Users')
         ->findById($id)
         ->first();

        return $user;
    }
}

Source: https://api.cakephp.org/3.6/class-Cake.Http.Session.html#_read

b3n10
  • 45
  • 7