Switch db connection dynamically
<p>For several console commands, I have the need to change databases so all my eloquent commands and queries run on the correct db (and server).</p>

<p>Ive seen a few solutions, the simplest seems to be changing the config like so:</p>

<pre><code>$new_connection = [
        'driver'    =&gt; 'mysql',
        'host'      =&gt; '127.0.0.1',
        'database'  =&gt; 'test_db',
        'username'  =&gt; 'test',
        'password'  =&gt; 'test',
        'charset'   =&gt; 'utf8',
        'collation' =&gt; 'utf8_general_ci',
        'prefix'    =&gt; '',
        'strict'    =&gt; false
];

config(['database.connections.mysql' =&gt; $new_connection]);
DB::purge('mysql');
</code></pre>

<p>The only issue (that I have noticed) is when I attempt to do transactions, more specifically, when I do transactions inside my acceptance tests in Codeception - they simply don't work.</p>

<p>The commands I use are:</p>

<pre><code>DB::connection()-&gt;beginTransaction(); // inside the _before function
</code></pre>

<p>and </p>

<pre><code>DB::connection()-&gt;rollBack(); // inside the _after function
</code></pre>