1

On top of every controller and routes.php I used:

use Illuminate\Support\Facades\Session;

In routes.php I set the session using:

Session::put('key', 'value');

In a controller I want to call the session value of key using:

echo Session::get('key');

But once I set a new value to key in routes.php and call it in a controller, I still get the first value and not the new one. If I echo the the session using Session::all() in routes.php after setting it, I see the new value, but in a controller it flips back to the first value. I even tried using below in routes.php before setting the new value, but without success.

Session::forget('key');

Am I forgetting something here?

Using regular PHP $_SESSION my routes.php looks like this:

$slug = $_SERVER['REQUEST_URI'];
$slug = explode('/', $slug[0]);

if(in_array($slug[1], Language::all()->lists('iso'))) {
    $_SESSION['language'] = $slug[1];
    if(!$slug[2]) {
        $_SESSION['slug'] = 'home';
        Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page']);
    } else {
        if($slug[2] != 'dashboard' && $slug[2] != 'migrate' && $slug[2] != 'form-send') {
            if (in_array($slug[2], ElementValue::where('element_field_id', 2)->lists('value_char')) && !isset($slug[3])) {
                $_SESSION['slug'] = $slug[2];
                Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page']);
            } else {
                $_SESSION['slug'] = 'home';
                Route::any('/{slug}', ['as' => 'pages.page', 'uses' => 'PagesController@page']);
            }
        }
    }
}
Alvin Bakker
  • 1,456
  • 21
  • 40
  • why are you setting the session in route.php and then using the value in the controller? If you are using controllers, any session values should be set in the controller or middleware. – GWed Nov 24 '15 at 14:14
  • post your routes.php code as well – GWed Nov 24 '15 at 14:19
  • Just added the routes part in my question – Alvin Bakker Nov 24 '15 at 14:33
  • hmm looks very 'un-laravel'. I'd suggest going through the docs and doing some tutorials. Routes.php should never look like this in laravel. Many better ways to do it like in middleware using the Request class – GWed Nov 24 '15 at 14:56

3 Answers3

4

Where in routes.php are you setting the session value? It sounds like you're doing something like this:

Session::put('key', 'value');

Route::get('my-route', 'MyController@doSomething');

and then doing this:

class MyController {
    public function doSomething()
    {
        Session::get('key');
    }
}

Is that correct? If so, read on...

I'm no expert on the Laravel request lifecycle (for more, see the documentation), but it doesn't surprise me that this doesn't work. The way I think about it is this: the routes.php file is loaded and executed early in the life cycle - probably first - since it tells the application what code to execute next (ie. what do when a particular request is received). And when I say "early in the life cycle", I mean early - like before sessions are initialized. I believe that the Session::put call is simply being ignored, since at the time when you're setting the value, the session does not exist.

You may want expand your question with a little more detail about what you're trying to accomplish - there has got to be a better way to do it.

EDIT - in response to the comments below...

I am not saying you should touch the $_SESSION superglobal - that's a bad idea because I'm not even sure that Laravel uses the native PHP session facility and you have no guarantee that whatever you do will continue to work in the future.

It's not clear what you're trying to do, but to me this sounds like a value that does not belong in the session.

By placing the Session::put in the routes.php file, it sounds like you have some value that's important and should be set for every session and every request

If that's the case, and it's a static value, then it's not a session value, it's a configuration value.

If, instead, it's a dynamic value and/or it changes depending on which user is associated with a session, then you can set it in one of several places:

  1. if you're using controller-based routing, you could set this in the controller constructor, although I wouldn't recommend it, because you will probably have to do it for several controllers, leading to code duplication

  2. if you're using closures in your routes, set it there. E.g.

    Route::get('some/route', function () {
        Session::put('key', 'value');
        // this works, because the closure isn't executed until after
        // the application is initialized
    });
    
  3. you could also do it in middleware

  4. or in a service provider (although I'm not certain that sessions would be available when the service providers are executed).

The best option is probably middleware - this would allow you to set (or calculate) the session value in one place in your code and also associate it with particular routes, if you don't need it for all routes.

Kryten
  • 15,230
  • 6
  • 45
  • 68
  • So you are actually saying if I want to set the session in routes,php I should just do it using the regular PHP `$_SESSION`? – Alvin Bakker Nov 24 '15 at 14:25
  • Or in the config as mentioned here: http://stackoverflow.com/questions/28417796/set-session-variable-in-laravel – Alvin Bakker Nov 24 '15 at 14:27
  • @AlvinBakker: laravel doesn't use the regular PHP `$_SESSION`, so you can't use it – Moppo Nov 24 '15 at 14:33
  • Well with this it works, just want to use it the laravel way. See my adapted question – Alvin Bakker Nov 24 '15 at 14:36
  • @Kryten is right, I've created an issue for this a while ago, but I believe this is intended behaviour: https://github.com/laravel/framework/issues/8244 – Steve Bauman Nov 24 '15 at 15:15
1

Don't use $_SESSION in laravel. Uses the laravel Session class. See the following post How to access the globals $_SESSION and $_COOKIE from a laravel app?

Also, all your if logic should not be living in routes.php. You should add that to middleware to filter your routes.

Also, you are really making this hard for yourself. Laravel provides most of what you need in convenient helper classes e.g. Request::url(), Request::getHost(), Request::getLocale(). Have a read through the docs and get familiar with "The Laravel Way" it will be much easier and things will then work as you expect.

Community
  • 1
  • 1
GWed
  • 15,167
  • 5
  • 62
  • 99
0

I moved the logic to the controller and now my routes are this simple:

Route::pattern('slug', '[a-zA-Z0-9\-_\/]+');
$slug = Request::path();
if(isset($slug)) {
    Route::any('/{slug}', 'PagesController@index')->where('slug', '[a-zA-Z0-9\-_\/]+');
}

The session is stored in the PagesController and used further in the application. Thanks for your help guys.

Alvin Bakker
  • 1,456
  • 21
  • 40