dongyue0225 2018-11-17 03:37
浏览 80

如何使用Laravel应用程序将用户ID存储在数据库的会话表中?

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 帮我写一个c++工程
    • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
    • ¥15 关于smbclient 库的使用
    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教