-
Notifications
You must be signed in to change notification settings - Fork 29
Connecting to a specific database based on the current tenant
Braden Keith edited this page Jan 28, 2019
·
2 revisions
Mohamed Said recently covered in his series "Diving Laravel" how Laravel configures database connections.
I wanted to customize that post here for how I'd recommend using the Multitenancy package to customize which database your application is connecting to.
His middleware code is what you need to change. Here's the before:
public function handle($request, Closure $next)
{
if($request->getHttpHost() == 'tenant1.app.com'){
config(['database.connections.tenant.database' => 'tenant1']);
DB::purge('tenant');
DB::reconnect('tenant');
}
return $next($request);
}
It should simply become:
public function handle($request, Closure $next)
{
if( app('multitenancy')->receiveTenantFromRequest()->domain == 'tenant1' ){
config(['database.connections.tenant.database' => 'tenant1']);
DB::purge('tenant');
DB::reconnect('tenant');
}
return $next($request);
}
This will utilize the Multitenancy singleton to retrieve the domain of the current tenant.
You could scale this pretty easily by adding the database credentials to the Tenant model, which would allow you to pass in the values dynamically.
public function handle($request, Closure $next)
{
$tenant = app('multitenancy')->receiveTenantFromRequest();
config(['database.connections.tenant.database' => $tenant->database]);
config(['database.connections.tenant.host' => $tenant->host]);
config(['database.connections.tenant.port' => $tenant->port]);
// ...
DB::purge('tenant');
DB::reconnect('tenant');
return $next($request);
}