Question

I want to add an extra column user_id on session table.

The reason is, some time there are spammer to sign up fake account, once I know that the user is spammer, I want to log the user out by deleting the session record.

Is it possible to achieve this?

Was it helpful?

Solution

This is the session migration schema:

Schema::create('sessions', function($table)
{
    $table->string('id')->unique();
    $table->text('payload');
    $table->integer('last_activity');
    $table->integer('user_id')->unsigned(); //// ADD IT!
});

You can add whatever column you like on it, Laravel won't mind.

Or you can create a new migration and make it add a column on that table.

$table->integer('user_id')->unsigned();

You can create a Model for it:

class SessionModel extends Eloquent {

}

And do whatever you need with it:

$session = SessionModel::find(Session::getId());
$session->user_id = 1;
$session->save();

But if you're thinking about adding more info to the payload, which is where Laravel keeps the session data, although I think it's possible, you'll have to dig a bit more in Laravel's code to do that.

OTHER TIPS

Short version of migration

if( Schema::hasTable('sessions') ) {
    $table->integer('user_id')->unsigned();
}

Need to check if exist session table. Or create it before:

php artisan session:table
php artisan migrate

https://laravel.com/docs/5.7/session#introduction

This is the session migration schema:

Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->unique();
        $table->integer('user_id')->nullable();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->text('device')->nullable();
        $table->text('payload');
        $table->integer('last_activity');
    });

To add the information to the payload after adding COLUMN to the TABLE, just change the DatabaseSessionHandler class.

path: vendor/laravel/framework/src/illuminate/Session

Ex:

1º Creates the function

protected function device()
{
    $agent = new \Jenssegers\Agent\Agent;

    if ($agent->isDesktop()){
        $device = 'desktop';
    }

    return $device;
}

2º add in function addRequestInformation (& $ payload)

protected function addRequestInformation(&$payload)
{
    if ($this->container->bound('request')) {
        $payload = array_merge($payload, [
            'ip_address' => $this->ipAddress(),
            'user_agent' => $this->userAgent(),
            'device' => $this->device(),
        ]);
    }

    return $this;
}

Ready, device added to the table when the user login.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top