1

Im trying Laravel 5 and cant get Session working. Im inside a Controller and this is what ive done on an fresh setup and fresh controller:

\Request::session()->put('test', 'x');
var_dump(\Request::session()->get('test'));

This works as long as session is being written, and once you comment the first line there session value is gone on the next request.

Similarly, ive tried this Session:: instead of Request::session() and still same result.

Panup Pong
  • 1,871
  • 2
  • 22
  • 44
Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70

2 Answers2

1

Ok ive found the solution myself thanks to 2 posts:

Laravel 5 - session doesn't work

Session not working in middleware Laravel 5


  1. After all the OMG buzz around Laravel being so so so simple lets dance in the rain!! the simplest thing in PHP such as $_SESSION now requires \Request::session() for which you need to user Request. then you need 2 different methods to save and get values from it instead of $_SESSION['x'] directly!!

  2. Laravel (genius super alien tech) saves session at TerminableMiddleware instead of on spot, but DOESNOT mentions it on https://laravel.com/docs/5.2/session. So you will need to explicitly call Session::save()!!

So there you go, 5 lines to do 1 line work of $_SESSION!

Community
  • 1
  • 1
Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70
0

if you are using 5.2, make sure your controller is governed by the 'web' middleware group either via the route

$route->group([ 'middleware' => ['web'] ....  

or by instantiating it in your controllers construct method;

$this->middleware('web');
Luke Snowden
  • 4,056
  • 2
  • 37
  • 70