简体   繁体   中英

Laravel 6 config()->get('database.connections.mysql') not matching DB:connection()

Prerequisites

In my local environment I am working with multiple tenants and Redis (Auth required).
To serve the project I am using Valet.

For this case I am addressing these two connections:

- basic_foo (is defined in my .env)
- tenant_foo (is the one to change to during a request)

Until now I successfully changed the connections like so:

config()->set('database.connections.mysql', 
       array_merge(
        config()->get('database.connections.mysql') , 
        ['database' => 'tenant_foo']
    ); 

Problem

However, now I am seeing an issue with the query builder, keeping or falling back to the basic connection.

I get the expected connection results of tenant_foo (same for Redis) when I run

dd(config()->get('database.connections.mysql'));

I get the wrong but apparently active results of basic_foo when I run

dd(\DB::connection()); // returns Illuminate\Database\MySqlConnection

So all in all the app will return this Illuminate\Database\QueryException

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'basic_foo.table_bar' doesn't exist...

where it should search for

'tenant_foo.table_bar'

Things that did not solve the problem yet

  • restarting Redis
  • reinstalling Redis
  • php artisan config:cache
  • php artisan cache:clear
  • php artisan route:clear
  • php artisan view:clear
  • php artisan optimize
  • composer dump-autoload

Simply changing the database name to tenant_foo like below is not enough, as the config array remains the same of basic_foo .

\DB::connection()->setDatabaseName('tenant_foo');

Thoughts

  • I want to change the config-array the of \DB::connection() , but I don't know another way than the config->set().
  • I installed Telescope could this affect the db connection?
  • Any other ideas?

To dynamically change database name you should use:

DB::disconnect(); 
Config::set('database.mysql.database', 'tenant_foo'); 
DB::reconnect();

This worked for me:

\DB::disconnect('mysql'); 

Config::set('database.connections.mysql.database', 'tenant_foo');

\DB::reconnect('mysql');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM