问题
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