Reputation: 1050
Within my app I have different businesses and those have a number of users. For example:
And so on..
Each business has its own separate database, so Users A, B and C access the same database, and Users D and E access a different database (Every tenant database is identical in structure, the only thing that differs is the data).
There is a main database that has this information for each user, so I know which database a user belongs.
'main' => array(
'driver' => 'mysql',
'host' => 'hostname',
'database' => 'main_database',
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
'tenant' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => DYNAMIC_DATABASE_NAME_GOES_HERE,
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
I need to find a way to do the following in Laravel:
How can I accomplish this in Laravel 5.4?
Upvotes: 0
Views: 2685
Reputation: 4435
This link has a very good example of what you are looking for.
1) Setup two connections in your database config.
'main' => array(
'driver' => 'mysql',
'host' => 'hostname',
'database' => 'database',
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
'tenant' => array(
'driver' => 'mysql',
'host' => '',
'database' => '',
'username' => '',
'password' => '',
'prefix' => '',
)
2) Then to switch the DB, put the following code in your filters or middleware. Considering you have Tenant
model for database connection info.
$tenant = Tenant::whereSubDomain($subdomain)->first();
Config::set('database.connections.tenant.host', $tenant ->host);
Config::set('database.connections.tenant.username', $tenant ->username);
Config::set('database.connections.tenant.password', $tenant ->password);
Config::set('database.connections.tenant.database', $tenant ->database);
//If you want to use query builder without having to specify the connection
Config::set('database.default', 'tenant');
\DB::purge('tenant');
\DB::reconnect('tenant');
dd(\DB::connection('tenant'));
3) Specify following in your models
//On models dealing with the main DB
protected $connection = 'main';
//On models dealing with tenant DBs
protected $connection = 'tenant';
Upvotes: 1