时间:2021-07-01 10:21:17 帮助过:6人阅读
下面是ajax调用的方法:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
echo json_encode(['result' => 1]);
exit;
}
echo json_encode(['result'=>0,'msg'=>'退出失败']);
exit;
}
下面是登录时给session的user赋值的代码
public function valid(Request $request)
{
$r = $request->all();
$validator = Validator::make($r,[
'username'=>'bail|required',
'password'=>'bail|required|integer',
]);
if ($validator->fails()) {
return redirect('admin/login')->withErrors($validator)->withInput();
}
$where = [
'name'=>$r['username'],
'pwd'=>md5($r['password']),
];
$hasExists = AdminModel::hasExists($where);
if (null !== $hasExists) {
$request->session()->put('user',json_encode(['name'=>$r['username']]));
return redirect('admin');
} else {
return redirect('admin/login')->with('hasExists','用户名或密码错误');
}
}
做用户退出登录,ajax调用删除session登录时设置的$request->session()->put('user','value');
使用了$request->session()->forget('user');然后跳转到login页
但是发现跳转后获取的session数据仍然是删除前的session状态,所以还是保持了登录状态。求教是我用法错误吗?
下面是ajax调用的方法:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
echo json_encode(['result' => 1]);
exit;
}
echo json_encode(['result'=>0,'msg'=>'退出失败']);
exit;
}
下面是登录时给session的user赋值的代码
public function valid(Request $request)
{
$r = $request->all();
$validator = Validator::make($r,[
'username'=>'bail|required',
'password'=>'bail|required|integer',
]);
if ($validator->fails()) {
return redirect('admin/login')->withErrors($validator)->withInput();
}
$where = [
'name'=>$r['username'],
'pwd'=>md5($r['password']),
];
$hasExists = AdminModel::hasExists($where);
if (null !== $hasExists) {
$request->session()->put('user',json_encode(['name'=>$r['username']]));
return redirect('admin');
} else {
return redirect('admin/login')->with('hasExists','用户名或密码错误');
}
}
建议楼主在了解一下Larave的Session机制,如果你的代码中途有exit,最好在它之前Session::save()一下