Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Session in Model

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.

like image 527
powtac Avatar asked Jan 04 '12 21:01

powtac


People also ask

How can use session in MVC model?

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?

How to pass session from Controller to View?

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.

Can we use session in view?

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.


2 Answers

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;
    } 
}
like image 59
powtac Avatar answered Oct 02 '22 09:10

powtac


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');
like image 24
Will Avatar answered Oct 02 '22 10:10

Will