tenancy / multi-tenant

Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously github.com/hyn/multi-tenant
https://tenancy.dev
MIT License
2.56k stars 394 forks source link

Force switch tenant connection based on provided fqdn #954

Closed ceswebmaster closed 4 years ago

ceswebmaster commented 4 years ago

I have a method lined up to handle incoming text messages from Plivo. I have a hostnames table with each host along with their phone number. The idea is to first lookup the matching phone number in that table to figure out which tenant to work with as far as storing the message. Once it's found I want to switch the DB connection over to that tenant so I can process some actions, but I can't figure out how to switch with the given fqdn.

Current code that doesn't work:

public function routeIncoming(Request $request){
      $host = DB::table('hostnames')
            ->where('phone_number', '=',$request->To)
            ->first();
        $tenancy = app(\Hyn\Tenancy\Environment::class);
        $hostname = app(\Hyn\Tenancy\Contracts\Hostname::class);
        $hostname->fqdn = $host->fqdn;
        $tenancy->hostname($hostname);
        $tenancy->tenant($hostname->website);
        config(['database.default' => 'tenant']);

        // Get Contact info
        $contact = DB::table('contacts')
            ->where('phone_number', '=', $request->From)
            ->first();
}

This currently produces the following error: InvalidArgumentException: Database [tenant] not configured. in file /home/../public_html/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php on line 152

ceswebmaster commented 4 years ago

All set. Was able to modify the connection by doing the following:

$hostname = DB::table('hostnames')->select('*')->where('phone_number', $request->To)->first();
if($hostname->fqdn != 'defaultdomain.com'){
  $dbname = DB::table('websites')->select('uuid')->where('id', $hostname->website_id)->first();

  Config::set("database.connections.tenant", [
    "driver"   => 'mysql',
    "host" => 'localhost',
    "database" => $dbname->uuid,
    "username" => env('DB_USERNAME'),
    "password" => env('DB_PASSWORD')
  ]);

  Config::set('database.default', 'tenant');
  DB::purge('tenant');
  DB::reconnect('tenant');
}
//Continue with contact info and storing phone logs
ArlonAntonius commented 4 years ago

Glad you figured it out 💪 Sorry that we were not fast enough to help you with this.