尽管设置了它,laravel 会话仍返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13760900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel session returning null inspite of setting it
提问by itachi
Just a simple function in native php
只是原生 php 中的一个简单函数
protected function some_function(){
session_start();
if(!isset($_SESSION['a']))
{
$_SESSION['a'] = 'some value';
return true;
} else {
return $_SESSION['a'];
}
}
on the 1st run, it will return bool(true) and then "some value"
as expected.
在第一次运行时,它将返回 bool(true) ,然后"some value"
按预期返回。
Applying the same to laravel session,
将相同的应用于 Laravel 会话,
protected function some_function(){
$a = Session::get('abc');
if(is_null($a)){
Session::put('abc', 'some value');
//return Session::get('abc');
return true;
} else {
return $a;
}
}
By logic, on the 1st run, $a will be null
. and then puts "some value"
in abc
key and returns bool(true) as expected.
按照逻辑,在第一次运行时, $a 将是null
。然后"some value"
输入abc
key 并按预期返回 bool(true) 。
Howeveron consequent access, the Session::get('abc')
returns null every time.so every attempt returns bool(true).
但是,在随后的访问中,Session::get('abc')
每次都返回 null。所以每次尝试都返回 bool(true)。
I assumed may be session wasn't writing properly so i checked with getting the key value right after setting it.
我认为可能是 session 没有正确写入,所以我在设置后立即检查了获取键值。
by commenting out the line in the above code, it returns whatever value i put in Session::put('abc')
. So there is no error in writing the data.
通过注释掉上面代码中的行,它返回我输入的任何值Session::put('abc')
。所以写入数据没有错误。
Problemhere is trying to retrieve the value always returns null
though i have set after the 1st request.
这里的问题是尝试检索值总是返回,null
尽管我在第一个请求之后设置了。
Am i missing something here?
我在这里错过了什么吗?
EDIT
编辑
Using database as the driver, The sessions does not get save in database. No error is outputted. Database implementation has been correct with sessions table schema as described in docs.
使用数据库作为驱动程序,会话不会保存在数据库中。没有错误输出。如文档中所述,会话表架构的数据库实现是正确的。
回答by aebersold
Try this snippet. Untested, but pretty sure it works.
试试这个片段。未经测试,但很确定它有效。
if(Session::has('abc'))
{
return Session::get('abc');
} else {
Session::put('abc', 'some value');
return true;
}
回答by Invincible
After going through many forum to solve same issue, I solved it by setting my session driver to database.
在通过许多论坛解决相同的问题后,我通过将会话驱动程序设置为数据库来解决它。
'driver' => 'database',
and created table in database
并在数据库中创建表
CREATE TABLE `sessions` (
`id` varchar(40) NOT NULL,
`last_activity` int(10) NOT NULL,
`data` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;