Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 database session - store additional attributes and user information

I'm using Yii2's DBSession class to store web application sessions into a database table, called session.

This table by default only has 3 columns - id, expire and data.

I'd like to store additional information into this table, like the user_id of a logged in user.

Edit: So there's a parent class called yii\web\MultiFieldSession but no examples about how it's used. I'll see what I can discover...

like image 266
JamesG Avatar asked Feb 06 '23 17:02

JamesG


1 Answers

create migration:

$this->createTable('session', [
    'id' => $this->char(40)->notNull(),
    'expire' => $this->integer(),
    'data' => $this->binary(),
    'user_id' => $this->integer()
]);

$this->addPrimaryKey('session_pk', 'session', 'id');

add this to config:

'components' => [
    'session' => [
        'class' => 'yii\web\DbSession',
        'writeCallback' => function($session){
            return [
                'user_id' => Yii::$app->user->id
            ];
        }
        // 'db' => 'mydb',  // the application component ID of the DB connection. Defaults to 'db'.
        // 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
    ],
like image 74
Vitaly Avatar answered Feb 10 '23 09:02

Vitaly