Database saved sessions - adding new data
Asked Answered
G

1

8

I am working with a database based session driver at the moment, to allow us to store some persistent data across our application,

we create the session like this:

Auth::loginUsingId($user->id);

$payload = [
    'user_id' => $user->id,
    'lobby_id' => $user->room_id,
    'name' => $user->name,
    'host' => $user->host,
    'avatar' => $user->avatar
];

session()->put('user', $payload);
session()->save();
$session_id = session()->getId();

$cookie = cookie('app_cookie', $session_id, 86400 * 30, null, null, false, false);

We use the cookie that is created as a way of identifying the user.

Above we are creating the initial session when a user submits a form we want to add to that current session which form the user has completed.

So I was thinking I would be able to do something like this,

session()->put('user.completed_forms', 'form-1');

I would have assumed this would have added a new key-value pair in the database, it would get encoded and the payload would then get updated in the database, however, I see that a new row entirely is created with a new id.

Am I doing something wrong is it possible to update database saved session payload without creating a new row in the database? As potentially a user-id could have 000s of rows, and we use the session id in the cookie so don't want to have write a new cookie every server request either.

Genetics answered 4/10, 2019 at 11:54 Comment(4)
I assume that the $user variable states that the user is logged in? or no user model/tableNolly
Session is key:value based. What you can do is session()->get('user'), edit your user then save it again session()->put('user',$user). Or, since you're using database driver, you can use DB::table('sessions')->where('column','value')->update([...])Olivia
I think session is not the way to do it. If you have load balancing and most probably you will have many servers or api instances. For this case you could use cache or database. You can use $user->id as primary key and just update that row on the database or on the cache. Since you use sessionId it always change for the same user on every session.Behoove
I strongly suggest you use Redis instead of database session. It is faster and not database performance killerEscarp
L
0

You still need to flush the session before you can login as another user.


//THIS IS THE PART YOU'RE MISSING
session()->flush();

//THEN THE REST OF YOUR CODE SHOULD WORK THE SAME WAY YOU WERE DOING IT
Auth::loginUsingId($user->id);

$payload = ... ETC
Lampe answered 9/9, 2024 at 8:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.