Accessing Session in Model
Asked Answered
T

4

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.

Tartrate answered 4/1, 2012 at 21:9 Comment(0)
T
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;
    } 
}
Tartrate answered 4/1, 2012 at 22:13 Comment(2)
As per my 3rd option, just because you can doesn't mean you should.Belkisbelknap
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.Toaster
I
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');
Inclination answered 11/4, 2013 at 13:51 Comment(0)
B
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;
   }
}

?>
Belkisbelknap answered 4/1, 2012 at 21:23 Comment(0)
S
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

Scanlan answered 27/10, 2018 at 17:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.