Laravel Session :: getId()在登录和注销时有所不同 [英] Laravel Session::getId() is different on login and logout
问题描述
我有表user_logins
来维护有关用户的多个登录信息
user_logins
的表结构: 'session_id',
'user_id',
'ip_address',
'user_agent',
'browser_name',
'location',
'login_at',
'is_active'
我有 UserEventSubscriber 侦听器,具有以下两个功能:
public function handleUserLogin($event) {
UserLogin::create([
'session_id'=>Session::getId(),
...
]);
}
我在handleUserLogin
函数中获得了Session::getId() = mpT6RDsl54JExkejrqf3fnYiFLzbR2pTb2qfNHBe
现在,当用户注销时,我想从user_logins表中更新/删除表条目,其中session_id = Session :: getId()
public function handleUserLogout($event) {
dd(Session::getId());
//UserLogin::where('session_id',Session::getId())->delete();
}
handleUserLogout函数中,我获得了不同的会话ID
Session::getId() qLYngAx1Vs8VBhxm0oCKZO3fDwun02UEXRyDm0Hi
,因此我无法更新/删除user_logins
表中的条目
我已经看到sessions
表的ID为qLYngAx1Vs8VBhxm0oCKZO3fDwun02UEXRyDm0Hi
,这与我退出登录功能的ID相同.
所以我的问题是,为什么我在用户登录功能上得到了不同的会话ID?以及我应该如何使用handleUserLogin和handleUserLogout函数中的Session::getId()
获取相同的会话ID.
我发现,需要从UserEventSubscriber listener with 2 functions like below :
public function handleUserLogin($event) {
UserLogin::create([
'session_id'=>Session::getId(),
...
]);
}
im getting Session::getId() = mpT6RDsl54JExkejrqf3fnYiFLzbR2pTb2qfNHBe
in handleUserLogin
function
now when user logout i want to update / delete the table entry from user_logins table where session_id = Session::getId()
public function handleUserLogout($event) {
dd(Session::getId());
//UserLogin::where('session_id',Session::getId())->delete();
}
on handleUserLogout function im getting a different session id
Session::getId() qLYngAx1Vs8VBhxm0oCKZO3fDwun02UEXRyDm0Hi
so im unable to update/delete entry in user_logins
table
i have seen sessions
table have id qLYngAx1Vs8VBhxm0oCKZO3fDwun02UEXRyDm0Hi
which is same as id i get on logout function .
so my question is why im getting a different session id on user login function ? and what should i do to get same session id using Session::getId()
in handleUserLogin and handleUserLogout function .
I have found that , need to override sendLoginResponse
from AuthenticatesUsers in Auth/LoginController
$request->session()->regenerate()
generates new session id after login , so if you want to get same id as before , comment out that line .
protected function sendLoginResponse(Request $request)
{
// $request->session()->regenerate(); <-- this line is generating new session after user login
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
这篇关于Laravel Session :: getId()在登录和注销时有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!