Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

e.bezdomnikov's avatar

Two session managers is it possible?

Hello everyone!

My case.

I have a main site, and now i implementing a administration panel (with Backpack package), and they both on one application layer. I need two different sessions one on main site and another on administration panel (my admin panel on www.site.com/admin). It is possible? Now I create a separated middleware group for /admin area and create middleware which replace SessionManager, Cookie, code below

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        app()->singleton('cookie', function ($app) {
            $config = $app->make('config')->get('admin-session');
            return (new CookieJar())->setDefaultPathAndDomain($config['path'], $config['domain'], $config['secure']);
        });


        app()->singleton('session', function ($app) {
            return new SessionManager($app);
        });

        app()->singleton('session.store', function ($app) {
            // First, we will create the session manager which is responsible for the
            // creation of the various session drivers when they are needed by the
            // application instance, and will resolve them on a lazy load basis.
            return $app->make('session')->driver();
        });
        
        $response = $next($request);

        return $response;

    }

It working, but I not sure that is a Laravel way.

Any suggestions?

Thx.

0 likes
3 replies
e.bezdomnikov's avatar

One more thing about my app. Users table is our clients. Users in /admin is Operators from different table and have own Auth driver.

But this is not a problem.

We need auth by client Id (for some purposes) but have in same time a admin access from Operator login in /admin area.

If we would use your way after logout from site side or from /admin side session will be regenerated and as result both sides will be logout.

And now I searching a way how to get different sessions.

e.bezdomnikov's avatar

If you have interest. I solve a problem by making my own Cookie and Session providers. Here they are.

<?php namespace App\Core\Providers;

use App\Core\Config\ConfigRequest;
use Illuminate\Cookie\CookieJar;

class CookieServiceProvider extends \Illuminate\Cookie\CookieServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('cookie', function ($app) {

            $config = $app->make('config')->get('session');

            $config = ConfigRequest::get("session", $config);

            return (new CookieJar())->setDefaultPathAndDomain($config['path'], $config['domain'], $config['secure']);
        });
    }
}
<?php namespace App\Core\Session;

use App\Core\Config\ConfigRequest;
use Illuminate\Session\CookieSessionHandler;
use Illuminate\Session\DatabaseSessionHandler;
use Illuminate\Session\EncryptedStore;
use Illuminate\Session\FileSessionHandler;
use Illuminate\Session\Store;

class SessionManager extends \Illuminate\Session\SessionManager
{
    private $sessionConfig;

    public function __construct(\Illuminate\Foundation\Application $app)
    {
        parent::__construct($app);

        $this->sessionConfig = ConfigRequest::get("session", $this->app['config']['session']);
    }

    /**
     * Create an instance of the "cookie" session driver.
     *
     * @return \Illuminate\Session\Store
     */
    protected function createCookieDriver()
    {
        return $this->buildSession(new CookieSessionHandler(
            $this->app['cookie'], $this->sessionConfig["lifetime"]
        ));
    }

    /**
     * Create an instance of the file session driver.
     *
     * @return \Illuminate\Session\Store
     */
    protected function createNativeDriver()
    {
        $lifetime = $this->sessionConfig["lifetime"];

        return $this->buildSession(new FileSessionHandler(
            $this->app['files'], $this->sessionConfig["files"], $lifetime
        ));
    }

    /**
     * Create an instance of the database session driver.
     *
     * @return \Illuminate\Session\Store
     */
    protected function createDatabaseDriver()
    {
        $table = $this->sessionConfig["table"];

        $lifetime = $this->sessionConfig["lifetime"];

        return $this->buildSession(new DatabaseSessionHandler(
            $this->getDatabaseConnection(), $table, $lifetime, $this->app
        ));
    }

    /**
     * Get the database connection for the database driver.
     *
     * @return \Illuminate\Database\Connection
     */
    protected function getDatabaseConnection()
    {
        $connection = $this->sessionConfig["connection"];

        return $this->app['db']->connection($connection);
    }

    /**
     * Create an instance of the Redis session driver.
     *
     * @return \Illuminate\Session\Store
     */
    protected function createRedisDriver()
    {
        $handler = $this->createCacheHandler('redis');

        $handler->getCache()->getStore()->setConnection(
            $this->sessionConfig["connection"]
        );

        return $this->buildSession($handler);
    }

    /**
     * Create the cache based session handler instance.
     *
     * @param  string  $driver
     * @return \Illuminate\Session\CacheBasedSessionHandler
     */
    protected function createCacheHandler($driver)
    {
        $store = $this->app['config']->get('session.store') ?: $driver;

        return new CacheBasedSessionHandler(
            clone $this->app['cache']->store($store),
            $this->sessionConfig["lifetime"]
        );
    }

    /**
     * Build the session instance.
     *
     * @param  \SessionHandlerInterface  $handler
     * @return \Illuminate\Session\Store
     */
    protected function buildSession($handler)
    {
        if ($this->sessionConfig["encrypt"]) {
            return $this->buildEncryptedSession($handler);
        } else {
            return new Store($this->sessionConfig["cookie"], $handler);
        }
    }

    /**
     * Build the encrypted session instance.
     *
     * @param  \SessionHandlerInterface  $handler
     * @return \Illuminate\Session\EncryptedStore
     */
    protected function buildEncryptedSession($handler)
    {
        return new EncryptedStore(
            $this->sessionConfig["cookie"], $handler, $this->app['encrypter']
        );
    }

    /**
     * Get the session configuration.
     *
     * @return array
     */
    public function getSessionConfig()
    {
        return $this->sessionConfig;
    }

    /**
     * Get the default session driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->sessionConfig["driver"];
    }

    /**
     * Set the default session driver name.
     *
     * @param  string  $name
     * @return void
     */
    public function setDefaultDriver($name)
    {
        ConfigRequest::set('session','driver', $name);
    }
}
<?php namespace App\Core\Config;

use Config;

class ConfigRequest
{
    public static function get($name, $default = null)
    {
        if ($configName = request()->segment(1))
        {
            if ($config = config( $configName . '.' . $name))
            {
                return $config;
            }
        }

        if (! is_null($default))
            return $default;

        return null;
    }

    public static function set($configName, $paramName, $paramValue)
    {
        if ($configPath = request()->segment(1))
        {
            if ($config = config( $configPath . '.' . $configName))
            {
                Config::set($configPath . '.' . $configName . '.' . $paramName, $paramValue);
            }
        }   
        Config::set($configName . '.' . $paramName, $paramValue);
    }
}

Maybe someone find it useful.

Please or to participate in this conversation.