Search code examples
laravelmulti-tenantmulti-database

Orchestral/tenanti multi database


I build an application for many tenants and each tenant has it's own database. The name of the database is the same as the tenants id.(the id exists out of five numbers). After authentication the user should be connected with his own database and redirected to his dashboard.

I tried to connect the user with his database with the following code, which I placed in Authenticate.php

if (!Auth::guest() && Auth::user()->tenant) {
        $user = Auth::id();
        Tenanti::driver('user')->asDefaultDatabase($user, 'users_{id}');
        Config::set('database.connections.mysql.database', 'user_'.$user); 
    }

The if statement checks in the main database if the logged in user is a tenant(boolean).

The config/database.php contains the following code:

 'tenants' => [
        'user_1' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',     // for user with id=1
            'database'  => '86097',     // for user with id=1
            'username'  => 'root', // for user with id=1
            'password'  => 'root', // for user with id=1
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
            ],
        ],

AppServiceProvider:

<?php namespace App\Providers;

use Orchestra\Support\Facades\Tenanti;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
{
    Tenanti::setupMultiDatabase('tenants', function (User $entity, array $template) {
        $template['database'] = "user_{$entity->getKey()}";

        return $template;
    });
}
}
?>

I don't get an error, but the connection hasn't changed. The user database is empty and therefore I shouldn't see any data when I log in with user_id=1 . Thanks in advance for helping.


Solution

  • The configuration should be:

    'tenants' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',     // for user with id=1
        'database'  => '86097',     // for user with id=1
        'username'  => 'root', // for user with id=1
        'password'  => 'root', // for user with id=1
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
    

    Other than that please replace Tenanti::setupMultiDatabase() with Tenanti::connection() (we have deprecated the old method).

    And change the following:

    Tenanti::driver('user')->asDefaultConnection(Auth::user(), 'tenants_{id}');

    Obviously if you want to use users_{id} you would then need to replace all tenants to users.