PHPackages                             quantumtecnology/multi-tenant - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. quantumtecnology/multi-tenant

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

quantumtecnology/multi-tenant
=============================

Service Basics Extension

0.2.0(3mo ago)026MITPHPPHP ^8.2CI passing

Since Oct 16Pushed 3mo agoCompare

[ Source](https://github.com/Quantum-Tecnology/Multi-Tenant)[ Packagist](https://packagist.org/packages/quantumtecnology/multi-tenant)[ Docs](http://www.gustavosantarosa.esy.es/)[ RSS](/packages/quantumtecnology-multi-tenant/feed)WikiDiscussions 0.x Synced today

READMEChangelogDependencies (18)Versions (10)Used By (0)

Laravel Multi-Tenant (QuantumTecnology\\Tenant)
===============================================

[](#laravel-multi-tenant-quantumtecnologytenant)

A small, flexible Laravel package to manage multi-tenant applications. It lets you switch the application context to a specific tenant, connect to its database using pluggable strategies, and optionally apply environment side-effects (like cache prefixes). The package also provides a convenient command to run tenant migrations per tenant, either synchronously or via queued batch jobs with automatic rollback on failures.

- Framework: Laravel 10–12 components
- PHP: 8.2+

Features
--------

[](#features)

- Pluggable connection strategy via TenantConnectionResolver contract
- Pluggable environment adjuster via TenantEnvironmentApplier contract
- Queue configuration applier to pin all queue storage to the central database (prevents tenant context from affecting enqueuing)
- Simple Tenant model with optional custom ID generator (via UniqueIdentifierInterface)
- Helper functions: tenant() and tenantLogAndPrint()
- Queue-aware tenant propagation for Jobs (payload carries tenant\_id; worker reactivates tenant before handling)
- Per-tenant migrations command (sync or queued batch) with progress tracking table
- Automatic rollback of already migrated tenants if a batch fails
- Publishable config and migrations; automatic creation of a "central" DB connection alias if missing

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

[](#installation)

Install via Composer:

```
composer require quantumtecnology/multi-tenant
```

The service provider is auto-discovered:

- QuantumTecnology\\Tenant\\TenantServiceProvider

Publishing
----------

[](#publishing)

Publish the configuration file:

```
php artisan vendor:publish --tag=tenant-config
```

This will create config/tenant.php in your application.

Publish the baseline migrations provided by the package:

```
php artisan vendor:publish --tag=tenant-migrations
```

This will publish:

- A tenants table migration
- A tenant\_migrations\_progress table migration (used to track migration batches/status)

Configuration (config/tenant.php)
---------------------------------

[](#configuration-configtenantphp)

Key options you can tweak:

- model.tenant: Your Tenant Eloquent model class. Defaults to QuantumTecnology\\Tenant\\Models\\Tenant.
- model.id\_generator: Class that implements UniqueIdentifierInterface to generate IDs (e.g. UUIDs) for new tenants.
- database.migrations: Directory containing your tenant migrations (e.g. database/migrations/tenant).
- database.seeder: Seeder class to run after tenant migrations when requested.
- table.progress: Table used to store migration progress and status (default: tenant\_migrations\_progress).
- queue.name: Queue name used by the package jobs (default: default).

Note: Ensure your database.default is a central connection. The package dynamically registers a separate connection for the active tenant when switching context.

How it works
------------

[](#how-it-works)

- TenantManager is responsible for switching to a tenant and reconnecting the database using a connection name determined by the resolver (defaults to tenant). It also delegates environment updates (e.g., cache prefixes) to the environment applier and stores the current tenant in the container as tenant.
- DefaultTenantConnectionResolver merges the tenant data over your base/default DB connection config to create the tenant connection config.
- DefaultTenantEnvironmentApplier sets cache/redis prefixes per tenant and binds the current tenant instance into the container.

### Accessing the current tenant

[](#accessing-the-current-tenant)

Use the helper:

```
$tenant = tenant(); // returns the current tenant bound in the container, or null
```

Or resolve directly from the container:

```
$tenant = app('tenant');
```

### Switching to a specific tenant (programmatically)

[](#switching-to-a-specific-tenant-programmatically)

You can manually define the active tenant anywhere in your app using the TenantManager. This will reconfigure the database connection for the tenant and apply environment side-effects (like cache prefixes).

```
use QuantumTecnology\Tenant\Support\TenantManager;

// Resolve your Tenant model from config
$model = config('tenant.model.tenant');

// Locate the tenant you want to work with
$tenant = $model::query()->firstWhere((new $model())->getTenantKeyName(), $tenantId);

if ($tenant) {
    // Switch the application context to this tenant
    app(TenantManager::class)->switchTo($tenant);

    // ... run your tenant-specific logic here ...
    // e.g. models, DB, cache, etc., will use the tenant context

    // Optionally, when finished, return to the central context
    app(TenantManager::class)->disconnect();
}
```

Notes:

- In a long-running process, always disconnect when you no longer need the tenant context to avoid leaking state to subsequent operations.
- In queued jobs, the package automatically propagates the tenant\_id and reapplies the tenant before handling the job.
- You can access the current tenant at any time via the tenant() helper or app('tenant').

### Identifying tenant via middleware

[](#identifying-tenant-via-middleware)

You can identify and switch to the correct tenant per request using a middleware in your application. Below is a simple example that supports subdomain, header, or route parameter identification.

Middleware example (App\\Http\\Middleware\\IdentifyTenantMiddleware.php):

```
