Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ranjeet's avatar

How to store users id in Session table Laravel 5

I want to check online users by storing user id in session table when user logged in i have made a session.table

php artisan session:table

i have added user_id column in migration file and it looks like this

<?php

use Illuminate\Database\Migrations\Migration;

class CreateSessionTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sessions', function($t)
        {
            $t->string('id')->unique();
            $t->text('payload');
            $t->integer('last_activity');
            $t->integer('user_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('sessions');
    }

}

Then i made migration

php artisan migrate

I have made model for it,, named online

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Online extends Model{
    protected $table = "sessions";
    protected $timestamps = false;
    protected $fillable = ['user_id'];
}

Now what i should do to store logged in user id into session table

0 likes
11 replies
christopher's avatar

Take a look at config/session.php You may want to change it to database.

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),
    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

Make also sure you read the Session Docs: http://laravel.com/docs/5.1/session

Ranjeet's avatar

@kayyyy I have not understand what you are saying,please can you explain abit more

my session.php file looks like this

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'database'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => 120,

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */

    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path().'/framework/sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => null,

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [2, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => 'laravel_session',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => null,

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => false,

];

Anyone can help me to solve this problem ?

bobbybouwmann's avatar

The table name of your "logged in users(sessions)" you used right now is the same table name as the session driver used by Laravel. Now you can simply update this table name in the config, but as long as you don't use it, you are fine ;)

To store it you need to perform an action when the users is logged in

Online::create([
    'field1' => $value1,
    'field2' => $value2,
    'user_id' => Auth::user()->id,
]);
1 like
pmall's avatar

The question is why do you want to do this. There must be a better way.

stayallive's avatar

You can override the Illuminate\Session\DatabaseSessionHandler write method in your own session driver to include the user_id field.

So you would create a App\Session\DatabaseSessionHandler:

namespace App\Session;
class DatabaseSessionHandler extends \Illuminate\Session\DatabaseSessionHandler
{
    /**
     * {@inheritDoc}
     */
    public function write($sessionId, $data)
    {
        $user_id = (auth()->check()) ? auth()->user()->id : null;

        if ($this->exists) {
            $this->getQuery()->where('id', $sessionId)->update([
                'payload' => base64_encode($data), 'last_activity' => time(), 'user_id' => $user_id,
            ]);
        } else {
            $this->getQuery()->insert([
                'id' => $sessionId, 'payload' => base64_encode($data), 'last_activity' => time(), 'user_id' => $user_id,
            ]);
        }

        $this->exists = true;
    }
}

Then you would need to create a service provider which registers this session driver:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Session\DatabaseSessionHandler;

class SessionServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->session->extend('app.database', function ($app) {
            $connectionName     = $this->app->config->get('session.connection');
            $databaseConnection = $app->app->db->connection($connectionName);

            $table = $databaseConnection->getTablePrefix() . $app['config']['session.table'];

            return new DatabaseSessionHandler($databaseConnection, $table);
        });
    }
}

This provider you must add to the app.php config file in the providers array (as the last one is just fine).

Then go to your session.php and replace the database driver with app.database and tada.

The user_id will be populated with the currently logged in user if any.

code is untested because I just wrote it in here... so check for syntax errors and replace the namespaces with your own.

9 likes
masterpowers's avatar

Hi Im using Multi Auth Everything works Fine except when Im Using the Admin table

Here is a Sample when i Get a Session with Users Table

Route::get('/user', function(){
    $user = Auth::type('user')->LoginUsingId(1);
    return $user->name;

});

But when i Hit My Router to Login as Admin it Wont Return me a Session of that Admin

Route::get('/admin', function(){
    $admin = Auth::type('admin')->LoginUsingId(1);
    
    return $admin->name;

});

BTW, Im Using Multi Auth by https://github.com/wuifdesign/laravel-multiauth Got 1 Table for user and 1 For Admin.

Here is my DatabaseSessionHandler

public function write($sessionId, $data)
    {
        $type = Auth::currentType();

        $user_id = (Auth::type($type)->check()) ? Auth::type($type)->id() : null;

        if ($this->exists) {
            $this->getQuery()->where('id', $sessionId)->update([
                'payload' => base64_encode($data), 'last_activity' => time(), 'user_id' => $user_id, 'user_type' => $type,
            ]);
        } else {
            $this->getQuery()->insert([
                'id' => $sessionId, 'payload' => base64_encode($data), 'last_activity' => time(), 'user_id' => $user_id, 'user_type' => $type,
            ]);
        }

        $this->exists = true;
    }

Dont Know What Im doing Wrong Please Help

masterpowers's avatar

Actually nothing wrong with my coding, the only problem is using the Auth functions.

lbm's avatar

Thank you @stayallive for that wonderful post. Just one small fix to your code in the DatabaseSessionHandler:

Remove that "$" before auth()->user()->id

 $user_id = (auth()->check()) ? auth()->user()->id : null;
1 like
mocheaz's avatar

Any idea how to do same thing on laravel 4.2

SlyDeath's avatar

I did it for myself (Laravel 7.*):

$this->app->session->extend('app.database', function ($app) {
            
        $connection_name = $this->app->config->get('session.connection');
        $connection      = $app->app->db->connection($connection_name);
        $table           = $this->app->config->get('session.table');
        $lifetime        = $this->app->config->get('session.lifetime');
            
        return new DatabaseSessionHandler($connection, $table, $lifetime, $this->app);
 });

Thank! Your answer really helped!

rubens2009's avatar

With Laravel 9. Using the answer from @stayallive and @masterpowers(without multi-auth repo)

Create SessionServiceProvider:

namespace App\Providers;

use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;
use App\Session\DatabaseSessionHandler;

class SessionServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Session::extend('database', function ($app) {
            $connection_name = $this->app->config->get('session.connection');
            $connection      = $app->app->db->connection($connection_name);
            $table           = $this->app->config->get('session.table');
            $lifetime        = $this->app->config->get('session.lifetime');

            return new DatabaseSessionHandler($connection, $table, $lifetime, $this->app);
        });
    }
}

Create DatabaseSessionHandler:

namespace App\Session;

use Illuminate\Contracts\Auth\Guard;

class DatabaseSessionHandler extends \Illuminate\Session\DatabaseSessionHandler
{
    /**
     * Add the user information to the session payload.
     *
     * @param  array  $payload
     * @return \Illuminate\Session\DatabaseSessionHandler
     */
    protected function addUserInformation(&$payload)
    {
        if ($this->container->bound(Guard::class)) {
            $payload['user_id'] = auth('web')->id();
            $payload['admin_id'] = auth('admin')->id();
        }

        return $this;
    }
}
3 likes

Please or to participate in this conversation.