Laravel 5 Multi-Tenancy App with separate databases - users have access to multiple installations

本秂侑毒 提交于 2019-12-02 19:17:37

Ok so what I ended up doing was having all user info, names of installations and mappings of what users can access what installations in one database, and all tenant info in seperate databases.

I then had two connections, mysql and mysql_tenant; where mysql_tenant database is not pre-set but dynamic.

The User, Installations and mappings model use the mysql connection, all others use mysql_tenant

Created a code for each installation, and used this as the name of the tenant database; storing this code in the session.

Used a middleware MultiTenant, to control the switching between installations using these key lines:

$tenant_id = session()->get('tenant');

\Config::set('database.connections.mysql_tenant.database', $dbname);
\DB::setDefaultConnection('mysql_tenant');

There's a lot more to it for building the method to switch etc, but this is the gist.

It is difficult to answer most of your question - as it is specific to your application and opinion based.

But the one bit I can answer is different models can have different database connections. So your user model uses the normal default connection - but your other models can use another connection:

class Example extends Model {

    protected $connection= 'second_db_connection';

}

Then in your DB connection file - you would have something like this:

return array(
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'second_db_connection' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
stephenthedev

Laravel 5 is advanced enough that you should be able to have simply one installation along with a strategic database, with well defined relations and keys. There is rarely ever a need for multiple databases.

If you can be more specific about your requirements I can provide a more specific answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!