Multi session tables in Laravel

梦想的初衷 提交于 2021-01-29 07:53:01

问题


i have setup a Laravel project with two guards wach with Hi own users table. Now i want to save the sessions into the database instead in a file. The Problem is that I cant save the session in a single table, because the user ID is not unique. How can I solve this problem? Thanks.


回答1:


I tried this. This working, but it exists a default session driver, so a user has a session in the default table and in the admin_sessions table.

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);
        });
    }

}


来源:https://stackoverflow.com/questions/53418791/multi-session-tables-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!