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

旧城冷巷雨未停 提交于 2020-01-11 11:18:32

问题


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?

回答1:


To dynamically change database name you should use:

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


来源:https://stackoverflow.com/questions/59580981/laravel-6-config-getdatabase-connections-mysql-not-matching-dbconnection

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