I want to make application with one "central" database and multiple "customers" databases (1 customer has 1 DB). I want to use lumen rest api framework. Let me explain logic behind databases and my issue.
Central DB (simplified):
Table: tenants
Columns: id(PK), id_tenant(FK), db_host, db_username, db_password, db_port, db_name
Customer DB (simplified):
Table: issues
Columns: id(PK), id_creator, issue_name, write_time
Lumen part
I have two models: Tenants
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class Tenants extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $connection = 'mysql2';
protected $fillable = [
'id_tenant'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
Issues:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class Issues extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
protected $connection = 'tenant';
protected $fillable = [
'id_issue'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
Also, I have created file in config/database.php:
<?php
return [
'default' => 'mysql',
'connections' => [
'mysql2' => [
'driver' => 'mysql',
'host' => 'dbhost',
'database' => 'dbName',
'username' => 'dbUser',
'password' => 'secretPass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'tenant' => [
'driver' => 'mysql',
'host' => '',
'port' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
]
],
]
?>
I have written 2 controllers (TenantsController and IssuesController), which are working with no issues, when i hardcode info about tenant database in config/database.php.
My issue is:
When I call route: api/tenant/1
(uses => TenantsController@getTenantById)
Lumen returns correct JSON with db data of requested tenant with id 1. This data I need to fill connection variables to another (customer) database, where table issues is located. How it is possible to set database connection 'tenant' to call route api/issues
from second DB and get list of all issues??
Note: Let's abstract from user authentication and secure API.
Thank you for help in advance.
</div>