Support the ongoing development of Laravel.io →
posted 4 years ago
Last updated 1 year ago.
0

Hi Dagord,

The way I recently tackled this issue was by having a database field databases with the credentials for each respective entity. You can link the sub-domain to a data-field (for example, a column called "subdomain" with value "two") so you can easily retrieve the database credentials for the active sub-domain / entity. Once you've found a way to retrieve the database credentials for the active sub-domain, you can switch to that database using this bit of code:

config(['database.connections.tenant' =>
	[
		'driver'    => 'mysql',
		'host'      => $tenant->host,
		'username'  => $tenant->username,
		'password'  => $tenant->password,
		'database'  => $tenant->database
	]
]);

After you've done that you can use that connection in your eloquent builds. For example:

User::connection('tenant')->find($id);

I'm not sure whether or not this is the best best possible way to do this, however it appears to be one of the only ways to dynamically create connections (on the fly) in Laravel. Hope this helps!

Last updated 4 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

dagord dagord Joined 6 Jun 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.