Wednesday, March 1, 2017

Laravel setting up one database per business

Within my app I have different businesses and those have a number of users. For example:

  • Business A has UserA, UserB and UserC
  • Business B has UserD and UserE

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:

  1. User signs in to the app
  2. After login I get the user database identifier/database name using the main database connection
  3. Set that specific database name within a connection called "tenant"
  4. App uses that tenant connection to load the data of that specific user/business

How can I accomplish this in Laravel 5.4?




via dan

Advertisement