Skip to content

Instantly share code, notes, and snippets.

@Jeff-P
Forked from lukevers/OTF.php
Created December 6, 2018 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeff-P/fc9131b46207e4e3cf4ccc1f8c1e75b2 to your computer and use it in GitHub Desktop.
Save Jeff-P/fc9131b46207e4e3cf4ccc1f8c1e75b2 to your computer and use it in GitHub Desktop.
Laravel 5 On The Fly Database Connections

This is a Laravel 5 class that I have at the location app/Database/OTF.php and use to connect to different databases on the fly.

// Using the same host/password/etc, just changing databases
$otf = new App\Database\OTF(['database' => 'kittens']);
// Get the users table
$users = $otf->getTable('users');
// Find the first user in the table
$first_user = $users->first();

Blog post here.

<?php namespace App\Database;
use Config;
use DB;
class OTF {
/**
* The name of the database we're connecting to on the fly.
*
* @var string $database
*/
protected $database;
/**
* The on the fly database connection.
*
* @var \Illuminate\Database\Connection
*/
protected $connection;
/**
* Create a new on the fly database connection.
*
* @param array $options
* @return void
*/
public function __construct($options = null)
{
// Set the database
$database = $options['database'];
$this->database = $database;
// Figure out the driver and get the default configuration for the driver
$driver = isset($options['driver']) ? $options['driver'] : Config::get("database.default");
$default = Config::get("database.connections.$driver");
// Loop through our default array and update options if we have non-defaults
foreach($default as $item => $value)
{
$default[$item] = isset($options[$item]) ? $options[$item] : $default[$item];
}
// Set the temporary configuration
Config::set("database.connections.$database", $default);
// Create the connection
$this->connection = DB::connection($database);
}
/**
* Get the on the fly connection.
*
* @return \Illuminate\Database\Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get a table from the on the fly connection.
*
* @var string $table
* @return \Illuminate\Database\Query\Builder
*/
public function getTable($table = null)
{
return $this->getConnection()->table($table);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment