Skip to content

Instantly share code, notes, and snippets.

@gamerwalt
Created October 24, 2015 03:40
Show Gist options
  • Save gamerwalt/b59deb7b4f119b3a96f8 to your computer and use it in GitHub Desktop.
Save gamerwalt/b59deb7b4f119b3a96f8 to your computer and use it in GitHub Desktop.
ConnectTenant Middleware
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('signin');
}
}
//get the current user
$this->user = $this->auth->user();
//get the tenant of the user
$tenant = $this->user->tenantUser->tenant;
//if you allow multiple tenants for a user,
//then check the count and do a necessary redirect for user to select organization to connect to
//set the database connections
$tenantDatabase = $tenant->tenantDatabase;
config(['database.connections.benta_tenant.database' => $tenantDatabase->database_name]);
config(['database.connections.benta_tenant.host' => $tenantDatabase->host]);
config(['database.connections.benta_tenant.username' => $tenantDatabase->username]);
config(['database.connections.benta_tenant.password' => $tenantDatabase->password]);
DB::setDefaultConnection('benta_tenant');
DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
DB::reconnect('benta_tenant');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment