PHPackages                             kashifleo/multi-db-bridge - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. kashifleo/multi-db-bridge

ActiveLibrary[Database &amp; ORM](/categories/database)

kashifleo/multi-db-bridge
=========================

A Laravel package for managing central and tenant databases simultaneously using explicit, secure tenant connections.

v1.0.3(4mo ago)067MITPHPPHP ^8.2 || ^8.3

Since Dec 17Pushed 3mo agoCompare

[ Source](https://github.com/kashifleo/multi-db-bridge)[ Packagist](https://packagist.org/packages/kashifleo/multi-db-bridge)[ RSS](/packages/kashifleo-multi-db-bridge/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (6)Used By (0)

Multi DB Manager for Laravel
============================

[](#multi-db-manager-for-laravel)

DbBridge is a Laravel package for managing central and tenant databases simultaneously using explicit, secure tenant connections.

Features
--------

[](#features)

- **Central-Managed Tenancy**: Single central database storing tenant credentials.
- **Explicit Connection**: No auto-magic middleware. You control when to connect.
- **Simultaneous Access**: Query `User::on('central')` and `Order::on('tenant')` at the same time.
- **Secure**: Credentials stored in DB, not separate `.env` files.
- **Job Support**: Full support for queues and jobs with automatic tenant context preservation.

Installation
------------

[](#installation)

```
composer require kashifleo/multi-db-bridge
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Kashifleo\MultiDBBridge\DbBridgeServiceProvider"
```

This will create `config/dbbridge.php`:

```
return [
    'central_connection' => 'mysql', // Your main connection
    'tenant_connection' => 'tenant', // The dynamic connection name
    'tenant_model' => App\Models\Tenant::class, // Your Tenant Model
    'tenant_migrations_path' => 'database/migrations/tenants', // Path to tenant migrations
    'tenant_database_prefix' => 'tenant_', // Prefix for tenant databases
];
```

Usage
-----

[](#usage)

### Tenant Model

[](#tenant-model)

Your App's Tenant model must implement `Kashifleo\MultiDBBridge\Contracts\DbBridgeConnectionContract`:

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Kashifleo\MultiDBBridge\Contracts\DbBridgeConnectionContract;

class Tenant extends Model implements DbBridgeConnectionContract
{
    public function getDatabaseDriver(): string { return $this->db_driver; }
    public function getDatabaseHost(): string { return $this->db_host; }
    public function getDatabasePort(): int { return $this->db_port; }
    public function getDatabaseName(): string { return $this->db_name; }
    public function getDatabaseUsername(): string { return $this->db_username; }
    public function getDatabasePassword(): string { return $this->db_password; }
}
```

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Kashifleo\MultiDBBridge\Contracts\DbBridgeConnectionContract;

class Tenant extends Model implements DbBridgeConnectionContract
{
    // Tenant connection name defined
    protected $connection  = 'tenant';

    public function getDatabaseDriver(): string { return $this->db_driver; }
    public function getDatabaseHost(): string { return $this->db_host; }
    public function getDatabasePort(): int { return $this->db_port; }
    public function getDatabaseName(): string { return $this->db_name; }
    public function getDatabaseUsername(): string { return $this->db_username; }
    public function getDatabasePassword(): string { return $this->db_password; }
}
```

```
// Query Tenant DB
$orders = \App\Models\Order::find(1);
```

### Database Management

[](#database-management)

You can programmatically manage tenant databases using the `DbBridge` facade. This is useful for onboarding flows.

```
use Kashifleo\MultiDBBridge\Facades\DbBridge;

// Generate a standard database name
// Pattern: {prefix}{id}_{slug}_{year}
$dbName = DbBridge::generateDatabaseName($tenant);
$tenant->update(['db_database' => $dbName]);

// Create the tenant's database
// This uses the 'tenant_database_prefix' from config if you use it in your model
DbBridge::createDatabase($tenant);

// Run migrations for the tenant
DbBridge::migrate($tenant);

// Drop the tenant's database (careful!)
DbBridge::dropDatabase($tenant);
```

### Connecting to a Tenant

[](#connecting-to-a-tenant)

```
use Kashifleo\MultiDBBridge\Facades\DbBridge;
use App\Models\Tenant;

$tenant = Tenant::find(1);

// Connect explicitly
DbBridge::connect($tenant);

// Check connection
if (DbBridge::isConnected()) {
    $current = DbBridge::current();
}

// Disconnect
DbBridge::disconnect();
```

### Simultaneous Database Usage

[](#simultaneous-database-usage)

```
// Query Central DB (default connection)
$users = \App\Models\User::on('mysql')->get(); // or default

// Query Tenant DB
$orders = \App\Models\Order::on('tenant')->get();
```

Tenant Database Migrations
--------------------------

[](#tenant-database-migrations)

This package provides a robust way to manage tenant database migrations separate from your central migrations.

### Configuration

[](#configuration-1)

Ensure your `config/dbbridge.php` has the migrations path configured:

```
'tenant_migrations_path' => 'database/migrations/tenants',
```

### Creating Tenant Migrations

[](#creating-tenant-migrations)

Use the `dbbridge:make-migration` command to create a migration file specifically for tenant databases. These files will be placed in the configured tenant migrations path.

```
# Create a new table
php artisan dbbridge:make-migration create_orders_table --create=orders

# Add a column to an existing table
php artisan dbbridge:make-migration add_status_to_orders_table --table=orders
```

### Running Tenant Migrations

[](#running-tenant-migrations)

Use the `dbbridge:migrate` command to run migrations on tenant databases.

**Migrate a Single Tenant:**

```
php artisan dbbridge:migrate --id=1
```

**Migrate All Tenants:**

```
php artisan dbbridge:migrate --all
```

The command dynamically connects to each tenant's database using the credentials stored in your central database and runs the migrations found in the `tenant_migrations_path`.

Middleware Usage
----------------

[](#middleware-usage)

The `EnsureDbBridgeConnected` middleware acts as a **Guard**. It aborts the request with a `403 Unauthorized` error if no tenant is connected. It does **not** automatically connect for you; it only ensures security.

### Registering the Middleware

[](#registering-the-middleware)

As this is a package, you must register the middleware in your application.

**For Laravel 11+ (`bootstrap/app.php`):**

```
use Kashifleo\MultiDBBridge\Middleware\EnsureDbBridgeConnected;

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'tenant.auth' => EnsureDbBridgeConnected::class,
    ]);
})
```

### Applying to Routes

[](#applying-to-routes)

Use it on routes that strictly require a tenant context (e.g., dashboard, orders).

```
Route::middleware([
    'web',
    'auth',
    'tenant.auth' // Ensures a tenant is connected before proceeding
])->group(function () {

    Route::get('/dashboard', function () {
        return DbBridge::current()->name . ' Dashboard';
    });

});
```

### Queue Support

[](#queue-support)

To use tenant connections inside Queued Jobs, you should pass the Tenant model to the Job's constructor and explicitly connect within the `handle` method. This ensures clarity and control.

```
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Kashifleo\MultiDBBridge\Facades\DbBridge;
use App\Models\Tenant as TenantModel;

class ProcessTenantOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $tenant;

    public function __construct(TenantModel $tenant)
    {
        $this->tenant = $tenant;
    }

    public function handle()
    {
        // Explicitly connect to the tenant
        DbBridge::connect($this->tenant);

        // Perform actions on the tenant database
        // ...

        // Optional: Disconnect if needed, though the worker will likely reset for next job
        // DbBridge::disconnect();
    }
}
```

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 87% of packages

Maintenance83

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

141d ago

PHP version history (2 changes)v1.0.0PHP ^8.3

v1.0.3PHP ^8.2 || ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/dafac3bec5e71969c67f126d691f4f97d73fca2e61e23c5da7f819b16ecefd8a?d=identicon)[kashifleo55](/maintainers/kashifleo55)

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kashifleo-multi-db-bridge/health.svg)

```
[![Health](https://phpackages.com/badges/kashifleo-multi-db-bridge/health.svg)](https://phpackages.com/packages/kashifleo-multi-db-bridge)
```

###  Alternatives

[watson/validating

Eloquent model validating trait.

9723.3M46](/packages/watson-validating)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[genealabs/laravel-pivot-events

This package introduces new eloquent events for sync(), attach(), detach() or updateExistingPivot() methods on BelongsToMany relation.

1404.9M8](/packages/genealabs-laravel-pivot-events)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
