Laravel Dynamic Database's

2019-09-10 21:58发布

问题:

(Laravel Config::set Persist Through Requests?)

After getting the answer below, I tried it out...

'default' => 'mysql_main',
    'connections' => [
        'mysql_main' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
        'mysql_company' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => Auth::user()->club->db_name,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

    ],

However, upon doing this inside the database.php folder under config I receive the following error...

Fatal error: Class 'Auth' not found in F:\trapstats_v5\config\database.php on line 73.

Is there another way to do dynamic database connections, based on the user, that will save through requests instead of doing config([database.connections.mysql_company.database' => Auth::user()->club->db_name]) every time I want to access the dynamic connection?

This question is similar to the answer of Dynamic database connection in Laravel. And if I do this answer as well I get the same sort of error except this time it is called Session instead of Auth.

回答1:

In your config files doing

 'database' => Auth::user()->club->db_name,

Is dangerous because Auth is probably not setup at the point your configuration files are read by Laravel, it needs your configuration files to lots of other things, so it should read them fist. What you can do, in, lets say a ServiceProvider, or some other helper class is to:

config('database.connections.mysql_company', ['database' => Auth::user()->club->db_name]);


回答2:

After doing some more reading and going around and asking many questions I have come up with a solution.

What I ended up doing was creating a middleware called Database that ran AFTER every other middleware finished. This allowed for use of all of the typical Laravel services (like Auth::user());

Database class Database { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!Auth::guest()) { config(['database.connections.club.database' => Auth::user()->club->db_name]); } return $next($request); } } And then for the route group I assign this middleware to it.