I'm using Laravel along with the recommended way of storing sessions in the database (https://laravel.com/docs/5.2/session). Everything's working correctly except for the fact that the user_id
field in the sessions
table is always being stored as NULL
.
After doing some research, I found an SO post that recommended using Guard
, the standard authentication library in Laravel to populate it. Here's the post:
Laravel sessions table user_id always null
The problem though is that the authentication for the Laravel app at hand is a bit unique, and so custom logic has to be used for it. With that said, I still want to populate the user ID in the sessions
table in the DB.
That same topic above noted that you can change the following line in the vendor/laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php
file to get it to work:
$payload['user_id'] = $this->userId();
I changed the line to the following:
$payload['user_id'] = session('id', null);
This does give me what I want, but changing the code in the core of the Laravel framework like that feels weird to me.
Is there a better way to store the user ID in the sessions table in the DB with Laravel without using Guard
and Laravel's built-in authentication?
Thank you.
Edit: To clarify a bit more, I change the file
line in config/session.php
to the following:
'driver' => env('SESSION_DRIVER', 'database'),
And then I changed the following line in .env
to database
:
SESSION_DRIVER=database
After that, I ran the following lines to create the sessions
table in the DB:
php artisan session:table
composer dump-autoload
php artisan migrate
That alone was enough to set up sessions in the DB. However, as I mentioned in the original post, because I'm not using Laravel's built-in authentication, I can't (seemingly) set the user_id
field with Guard.
Thanks again.