1

I am looking for kind help.

I make a fresh installation of Laravel (5.2.15 by this time). I'm not using Homested. I chmod 'storage' directory and subdirectories, as documentation suggests, giving write permission. Session is configured as default, did not touch anything. So session driver is 'file' and path is 'framework/sessions'.

I write these test routes:

Route::get('/', function () {
    session(["test" => "ok"]);
    return view('welcome');
});

Route::get('/2', function () {
    print "session = ".session('test');exit();
});

Shouldn't it be enough to see session working? session('test') is null, and no file is written in framework/sessions. Chmoded 777 framework/sessions folder to be sure, nothing changed.

I'm a newbie at Laravel.. maybe I am missing something? Do i need to set these vars in config/session.php?

'path' => '/',
'domain' => null,

Thank you

Marco
  • 759
  • 3
  • 9
  • 22
  • 3
    Possible duplicate of [Laravel - Session store not set on request](http://stackoverflow.com/questions/34449770/laravel-session-store-not-set-on-request) – Bogdan Feb 13 '16 at 18:02
  • 2
    Check out the linked duplicate. Your routes should be defined inside the `web` middleware group if you want sessions. – patricus Feb 13 '16 at 18:42

2 Answers2

5

If you open your app/Http/Kernel.php, you will see that session class is a part of 'web' group, so it's not included by default:

 protected $middlewareGroups = [
        'web' => [
        ...
            \Illuminate\Session\Middleware\StartSession::class,
        ...
        ]
 ]

Therefore, you have to wrap your routes in a group with 'web' middleware or add 'web' middleware to each route separately:

Route::group(['middleware' => ['web']], function() {
    Route::get('/', function () {
        session()->put('test', 'ok');
        return view('welcome');
    });

    Route::get('/2', function () {
        return 'session = ' . session('test');
   });
}
Denis Mysenko
  • 6,366
  • 1
  • 24
  • 33
  • Thank you, that solved my problem. I read the whole documentation but it wasn't clear to me this step was necessary. At all. Thank you. – Marco Feb 14 '16 at 08:37
2

Try this :

Route::get('/', function () {
    Session::put('test', 'ok');
    return view('welcome');
});

Route::get('/2', function () {
    print "session = ".Session::get('test');exit();
});
BKF
  • 1,298
  • 4
  • 16
  • 35