I am trying to store the user’s geolocation information in an extra column on sessions table.
I use Fortify for authentication.
I created an extra column on sessions table for that.
migration:
public function up(): void
{
Schema::table('sessions', function (Blueprint $table) {
$table->json('geolocation')->after('user_agent')->nullable();
});
}
Then I created a Session model which accesses the session table:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Session extends Model
{
use HasFactory;
protected $casts = [
'id' => 'string',
'user_agent' => 'collection',
'geolocation' => 'collection'
];
protected $fillable = [
'geolocation',
'created_at'
];
}
I created a listener for successfull login event. In the handle method, I try to get the session id to match the session with the row on the database. However session()->id()
or session()->getId()
return a different value which does not exist in the sessions table.
The question is;
What should I do in order to be able to update the active session’s database column?
What alternative approach might be tried?
I try to match the user’s active session with the row on the sessions table and update a column of it.
Added Listener:
public function handle(Login $event): void
{
Log::debug(session()->getId());
}
Listener logs:
eLCe6agjjZaBeZyDVmck5B8JG1o8zGRMPgnGPza1
Only session id on the table:
0yWGas97v5Aupg7mQ6YuchlEl53EJstfn1mQpfvq
2
Answers
For the people facing the same issue, the problem is about Fortify actually. In the handle method of PrepareAuthenticatedSession action, there is one line of code causing that.
After commenting this line, I can get the same id from both database and session helper. Thanks for your comments anyway.
You can get the current request session ID using
request()->session()->id()
. Use the session ID to update the record to your session table