Skip to content

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 build upon 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 field 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]);
    // ...

    DB::purge('tenant');

    DB::reconnect('tenant');

    return $next($request);
}
Clone this wiki locally