3
votes

Just a simple function in native 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.

Applying the same to laravel session,

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.

However on consequent access, the Session::get('abc') returns null every time. so every attempt returns bool(true).

I assumed may be session wasn't writing properly so i checked with getting the key value right after setting it.

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.

Problem here is trying to retrieve the value always returns null though i have set after the 1st request.

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.

2
Have you setup your session configuration correctly? For example, is the application key set? laravel.com/docs/session/config - Niklas Modess
@nerdklers I am using the file driver as of now. application key is set. - itachi
are you still having this issue, because I am having similar issues - mattl
@mattl No. I couldn't resolved it and had to make my own library. But the newest version doesn't have it and working pretty well. One thing to consider. While putting something in session, do not exit prematurely. Suppose if i put something in session and call dd(), it won't get save. If you indeed need to save, you need to call Session::save() manuely after putting the value but before exiting. Let me know if it was hard to follow. - itachi
I've also found situations where using a default response with the Session::get() method has replaced other put methods that were acting up. - mattl

2 Answers

0
votes

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;        
}
0
votes

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;