title: How to change/resolve DB connections in Laravel 5 dynamically?
body: <p>I am working on an application which is multi tenant multi DB architecture which basically means that every tenant has his own database instead of all the tenants living in the same DB.</p>
  
  <p>Now I am constantly struggling with the fact that I am not able to change the DB connections successfully and I am not sure what is right way to do it.</p>
  
  <p>My database config file looks like so:</p>
  
  <pre><code>'connections' =&gt; [
  
      'archive' =&gt; [
          'driver'    =&gt; 'mysql',
          'host'      =&gt; env('DB_HOST', 'localhost'),
          'database'  =&gt; env('DB_DATABASE', 'forge'),
          'username'  =&gt; env('DB_USERNAME', 'forge'),
          'password'  =&gt; env('DB_PASSWORD', ''),
          'charset'   =&gt; 'utf8',
          'collation' =&gt; 'utf8_unicode_ci',
          'prefix'    =&gt; '',
          'strict'    =&gt; false,
      ],
  
      'tenant' =&gt; [
          'driver'    =&gt; 'mysql',
          'host'      =&gt; env('DB_HOST', 'localhost'),
          'database'  =&gt; env('DB_DATABASE', 'forge'),
          'username'  =&gt; env('DB_USERNAME', 'forge'),
          'password'  =&gt; env('DB_PASSWORD', ''),
          'charset'   =&gt; 'utf8',
          'collation' =&gt; 'utf8_unicode_ci',
          'prefix'    =&gt; '',
          'strict'    =&gt; false,
      ],
  
  ],
  </code></pre>
  
  <p>So basically the main DB is archive and it holds all the tenant (company) information and when a user wants to log in, he basically provides the tenant (company) username first, then provides his own login credentials. This way I know which database I should connect to and authenticate the user from. One the authentication is successful, I save the username of the tenant to a session <code>username</code> variable which is in turn used by a middleware I have written. So basically if the session has a <code>username</code> variable, I know to switch to the database every time a request is fired from that user. This way I am keeping track of which request is supposed to connect to which database.</p>
  
  <p>Login logic:</p>
  
  <pre><code>$this-&gt;changeDb($request-&gt;input('username'));
  $this-&gt;saveUsernameToSession($request);
  
  if (\Auth::attempt(['email' =&gt; $request-&gt;input('email'),
                   'password' =&gt; $request-&gt;input('password')])) {
      // Authentication passed...
      return redirect('/');
  }else{
      // If the auth atttemp is not successful
      // Set default DB as the main one again.
      $request-&gt;session()-&gt;pull('username');
  }
  </code></pre>
  
  <p>Now the <code>changeDB()</code> method is the one I am interested in and am not sure if I am doing it right.</p>
  
  <pre><code>\Config::set('database.connections.tenant.database', $username);
  \Config::set('database.default', 'tenant');
  </code></pre>
  
  <p>So this is what it does behind the scenes. It basically changes the tenant connection in the database config file to the username of the tenant, because that is same as the database of the tenant. Then it sets the default database to the tenant connection.</p>
  
  <p>Is this the correct way of resolving the DB connection? Or are there other ways I am not aware of. Maybe Laravel provides some methods internally which I can use to switch/resolve database connections.</p>
  
  <p>The login works fine but the reason I am concerned is that many of the other things don't work as fine for example, I ran in to this problem when trying to seed fake tenants and seeding their fake users.</p>
  
  <p><a href="https://stackoverflow.com/questions/32989103/seeder-runs-fine-the-first-time-but-does-not-do-some-tasks-in-the-subsequent-loo">Seeder runs fine the first time but does not do some tasks in the subsequent loops in Laravel 5?</a></p>
  
  <p>I was using the same approach that I am using in the login but somehow it did not work. And although the answer provided solved my issue I am still not sure how?</p>
  
  <p>Also I was trying to use a similar approach in a controller method to change DBs and it did not work the way I expected again:</p>
  
  <pre><code>public function showUsersForTenant($id)
  {
      $tenant = Tenant::findOrFail($id);
  
      \Config::set('database.connections.tenants.database', $tenant-&gt;username);
  
      $users = User::on('tenant')-&gt;get();
  
      return response()-&gt;json($users, 200);
  }
  </code></pre>
  
  <p>This is supposed to return all the users for a particular tenant (company) to the super admin of the system who is connected to the main database. But it does not connect to the tenant database and keeps returning users from the main DB.</p>
  
  <p>There are some packages out there which support multi tenancy multi database approach but since I am a novice developer, I cannot make much sense out of their repositories and how THEY are changing/resolving the DB connection on the fly.</p>
  
  <p><a href="https://github.com/orchestral/tenanti" rel="nofollow noreferrer">https://github.com/orchestral/tenanti</a></p>
  
  <p><a href="https://github.com/laraflock/multi-tenant" rel="nofollow noreferrer">https://github.com/laraflock/multi-tenant</a></p>
  
  <p><a href="https://github.com/uxweb/laravel-multi-db" rel="nofollow noreferrer">https://github.com/uxweb/laravel-multi-db</a></p>
  
  <p>So how to change/switch/resolve connections successfully in Laravel 5?</p>