Arjun
Arjun

Reputation: 1439

Dynamic Database change in Laravel

I'm using DB::disconnect and DB::reconnection for connect database for multi tenant system in Laravel 5.2.

The code is as:

DB::disconnect();
Config::set('database.connections.mysql', $config);
DB::reconnect();

Where $config is an array of configurations to be set, this is working fine when I have to change the only database name, but when I want to change the prefix for the database it is not working, every time it takes old database.

I have tried to config:cache from the Middleware where I change the connection but it removes all input variables.

So, What Can I do to change prefix of DB connection? Any help?

Upvotes: 1

Views: 786

Answers (1)

user8555937
user8555937

Reputation: 2387

You'll need to purge the cache of the database object:

// Will disconnect automatically
DB::purge('mysql');

// Register new config
Config::set('database.connections.mysql', $config);

// Will reconnect automatically
DB::table('table')->get();

Upvotes: 3

Related Questions