Ad

October CMS Sessions Are Breaking?

- 1 answer

I've been trying to create a middleware in a plugin in October CMS, that takes from the input a value and stores it in session to be periodically displayed in a template.

Middleware function:

  public function handle($request, Closure $next)
  {
      session()->put('foo', input('foo'));
      logger('StartSession: foo: ', [session('foo')]);
      return $next($request);
  }

Registering middleware in plugin.php

    public function register()
    {
    $this->app->make('Illuminate\Contracts\Http\Kernel')->prependMiddleware('October\Demo\Middleware\StartSession');
    }

Method in plugin for accessing session

    public function registerMarkupTags()
    {
       return [
           'functions' => [
               'session' => [Session::class, 'get']
            ]
       ];
    }

Usage in demo theme

<h1>{{ session('foo') }}</h1>

This works on the first run. If I put foo as query string foo is displayed on the page. However on a second run if I changed the query string to bar, foo persists on the page.

Here is an example of the issue in a fresh installed October Instance

https://github.com/reed-josh/october-session-issue

Ad

Answer

Hmm may be your middleware is executed before session is initialised not sure

you can add your session data after all middleware executed

class StartSession
{
  public function handle($request, Closure $next)
  {
    $response = $next($request);

    // if we do not pass data hold old value 
    // do not override it with null
    if(input('foo')) {
        session()->put('foo', input('foo'));
    }

    logger('StartSession: foo: ', [session('foo')]);
    return $response;
  }
}

Like this

but make sure how session works you add session using get params it will not directly reflect it will reflect in your next request.

Also I noticed that you did not add condition for input its better add it because other wise it will set null if no param is passed and your session data override unnecessarily.

if any doubt please comment.

Ad
source: stackoverflow.com
Ad