3

I am developing a multi-tenant application using Laravel-5.2 Each tenant will have a separate database. Each tenant has their separate subdomain. I detect tenants using their subdomains.

I have setup models Tenant and DatabaseConnection where Tenant hasOne DatabaseConnection and DatabaseConnection belongsTo Tenant. The DB connections for tenants are set dynamically from BeforeMiddleware. These work perfectly well.

Now I want to use artisan tinker for the tenants. But if I run php artisan tinker it connects to the Tenant whose DB credentials are present in the .env file.

So I am trying to make a console command for the same. Here's what I have achieved so far.

class ClientTinker extends Command {

    protected $name = 'cdb:tinker';

    public function fire()
    {
        // get the subdomain
        $subdomain = $this->argument('subdomain');

        // get the client
        $client = Tenant::whereSubdomain($subdomain)->first();

        $connection = $client->databaseConnection();
        // $connection contains the database server, database name, user name, and password.
        // dynamically set connections here. *How?*
        ...

        // *I need to call tinker here. How?* 
    }

    protected function getArguments()
    {
        return [
            ['subdomain', InputArgument::REQUIRED, 'Subdomain of the tenant.'],
        ];
    }

So how do I set the DB connections for specific tenant and how do I run tinker?

1 Answers1

2

After you get the $connection variable in fire(), do this

DB::purge('mysql');

Config::set('database.connections.mysql.host', $connection->server);
Config::set('database.connections.mysql.database', $connection->database);
Config::set('database.connections.mysql.username', $connection->username);
Config::set('database.connections.mysql.password', $connection->password);
// I am assuming the variable names in $connection object here, as you have not specified them in your question.

Artisan::call('tinker');

See if this works for you.

linuxartisan
  • 2,396
  • 3
  • 21
  • 40