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.
A Session is a web term and the Model should be completely agnostic of it. You should pass the information that the Model requires from the Controller which has access to the Session. So check this out: public IQueryable<EstudentsViewModel> GetEstudentsProjected(decimal?
To pass the strongly typed data from Controller to View using session, we have to make a model class then populate its properties with some data and then pass that data to the session as Value. Selecting the Key's name is the programmer's choice.
Could we use a session object in our view? Answer- The answer is yes. Let me explain how, I can use it and retrieve it in my view.
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;
}
}
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With