Create a new database connection in your databse.php
'connections' => [
'new_db_connection' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_NEW', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'old_db_connection' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_OLD', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
]
Create helper method
static function getDatabaseName()
{
// Apply your condition and return databse
if(url('/') === 'http://localhost:8001'){
return 'new_db_connection';
} else {
return 'old_db_connection';
}
}
Using query builder
$databaseName = Helper::getDatabaseName();
DB::connection($databaseName)
->table('your table name')
->select('*')
->get();
Using model
<?php
namespace App\Models;
use App\Helper;
use Illuminate\Database\Eloquent\Model;
class Test extends Model {
public function __construct()
{
// You can apply the below variable dynamically and model
// will use that new connection
$this->connection = Helper::getDatabaseName();
}
protected $table = "users";
}