Laravel: connect to databases dynamically

Laravel: connect to databases dynamically

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Dynamic Database Connections in Laravel

Static configuration files are convenient, but they break down when your application's data sources change at runtime. The standard config/database.php file defines connections for specific environments like mysql, pgsql, or sqlite. However, scenarios exist where a single request might need to talk to an entirely different database—perhaps one selected by a user ID, a dynamic environment variable, or a microservice handoff. When the target database is not known until execution time, you cannot rely on predefined connection names. You must instantiate a connection directly using the DB facade's lower-level methods.

Laravel provides exactly this capability through the createConnection method. This approach bypasses the need to register a new connection in your config file or even define it globally. It allows you to pass an associative array of configuration parameters directly to the database engine, granting you full control over the driver, host, port, username, and password for that specific moment.

Here is how you implement this within a controller or service class:

use Illuminate\Support\Facades\DB;

// Define the dynamic connection details based on user input or logic
$connectionDetails = [
    'driver' => 'mysql',
    'host'   => env('DYNAMIC_DB_HOST', 'localhost'),
    'port'   => 3306,
    'database' => $requestedDatabaseName,
    'username' => $requestedUsername,
    'password' => $requestedPassword,
];

// Instantiate a fresh PDO connection
$connection = DB::createConnection($connectionDetails);

// You can now interact with this specific connection instance
// without affecting the default or global database state.
$result = $connection->table('users')->get();

The critical distinction here is understanding what $connection represents versus DB. The DB facade acts as a singleton wrapper around your primary, configured connection (usually defined in config/database.php). When you call createConnection, you are essentially constructing a new PDO object bound to your custom configuration. You can then delegate query execution to this instance.

A significant trade-off with this approach is the loss of global transaction management. Because DB::createConnection returns an isolated connection instance, it does not automatically participate in the active transaction of the default Laravel application connection. If your dynamic query needs to be part of a broader atomic operation involving the main database, you must manually commit or roll back that specific connection's work after execution. Failing to do so can lead to data inconsistency if the dynamic operation fails mid-way.

Furthermore, while this method offers flexibility, it introduces security considerations. If the dynamic connection details come from user input without strict validation, you risk SQL injection or unauthorized access to other databases on the server. Always sanitize and validate the host, database name, and credentials before passing them to createConnection.

For more complex scenarios involving multiple databases with varying configurations, consider using a "master-slave" style architecture or leveraging Laravel's multi-database support features if you are running version 5.1 or later. However, for ad-hoc connections driven by runtime variables, DB::createConnection remains the most direct and effective tool available to bridge the gap between static configuration and dynamic requirements.

Our network