Laravel中的多会话表

时间:2018-11-21 18:51:58

标签: php database laravel session

我已经建立了一个Laravel项目,其中有两个带有Hi自己的用户表的后卫。现在我想将会话保存到数据库中而不是文件中。问题是我无法将会话保存在单个表中,因为用户ID不是唯一的。 我怎么解决这个问题?谢谢。

1 个答案:

答案 0 :(得分:0)

我尝试过了。可以使用,但是它存在默认的会话驱动程序,因此用户在默认表和admin_sessions表中都有一个会话。

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        Administrator::class => UserPolicy::class,
    ];

    public function boot()
    {
        $this->registerPolicies();

        Auth::extend('admin_session', function ($app, $name, array $config) {

            $provider = Auth::createUserProvider($config['provider']);
            $guard = new SessionGuard($name, $provider, $app->session->driver('admin_database'));

            if (method_exists($guard, 'setCookieJar')) {
                $guard->setCookieJar($this->app['cookie']);
            }

            if (method_exists($guard, 'setDispatcher')) {
                $guard->setDispatcher($this->app['events']);
            }

            if (method_exists($guard, 'setRequest')) {
                $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
            }

            return $guard;
    }
}


class SessionServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }


    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->session->extend('admin_database', function ($app) {

            $table = 'administrator_sessions';

            // This is not workin, because I don't have the user her.
            /*if (auth()->user() instanceof Customer) {
                $table = 'customer_sessions';
            }
            else if (auth()->user() instanceof Administrator){
                $table = 'administrator_sessions';
            }*/

            $lifetime = $app['config']['session.lifetime'];
            $connection = $app['db']->connection($app['config']['session.connection']);

            return new DatabaseSessionHandler($connection, $table, $lifetime, $app);
        });
    }

}