Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 576
leopold Avatar asked Nov 22 '25 02:11

leopold


1 Answers

To dynamically change database name you should use:

DB::disconnect(); 
Config::set('database.mysql.database', 'tenant_foo'); 
DB::reconnect();
like image 195
Marcin Nabiałek Avatar answered Nov 24 '25 16:11

Marcin Nabiałek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!