Search code examples
phplaravelsqlitesessionlaravel-session

Laravel doesn't store additional session attribute in database


I'm trying to store a specific attribute in the sessions table of the user by using the laravel session logic.

Sessions Table Migration

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

ENV Config

APP_NAME=Laravel
APP_ENV=local
APP_KEY={KEY}
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=sqlite

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=database
SESSION_LIFETIME=120

Code

Route::post('/set-event', function(Request $request){
    Session::put('activeEvent', $request->get('event'));
    Session::save();
    return redirect()->route('home');
});

Every attribute in the sessions table gets updated but the "activeEvent" attribute is always null.

"$request->get('event')" returns an integer of the selected event. Already tried it by set the datatype of the activeEvent to integer.

Also tried it with the following snipets:

$request->session()->push
$request->session()->put
$request->session()->keep

Nothing worked. How can I store the activeEvent attribute in the database? Or isn't this possible?

I'm using PHP7.2 / Laravel 5.7 / SQLITE


Solution

  • It seems you have a wrong idea about how database driver for Laravel Session works. Each row of your sessions table represents all session data for one user. When you do Session::put('activeEvent', $value); it stores this 'activeEvent' => $value key/value pair into payload column.

    You don't need to alter this table to provide columns for each key you want to store - database session driver will serialize all the key/value pairs and put it into payload column.

    So in your case, revert sessions table migration to the way it was when you first generated it with php artisan session:table command. And work with Session as usual: put() to store, get() to read:

    Route::post('/set-event', function(Request $request){
        Session::put('activeEvent', $request->get('event'));
    
        return redirect()->route('home');
    });
    
    ...
    
    // Somewhere when you need to retrieve the value
    $activeEvent = Session::get('activeEvent');