Download the PHP package our-edu/multi-tenant without Composer
On this page you can find all versions of the php package our-edu/multi-tenant. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download our-edu/multi-tenant
More information about our-edu/multi-tenant
Files in our-edu/multi-tenant
Package multi-tenant
Short Description Shared multi-tenant infrastructure for OurEdu Laravel services (tenant context, global scope, traits, middleware).
License MIT
Homepage https://github.com/ouredu/multi-tenant
Informations about the package multi-tenant
Laravel Multi-Tenant
A Laravel package for building multi-tenant applications. This package provides tenant context management, automatic query scoping, and model traits for seamless multi-tenancy support.
Features
- Tenant Context - Centralized tenant state management across requests, jobs, and commands
- Automatic Query Scoping - All queries automatically filtered by tenant
- Model Trait - Simple
HasTenanttrait for tenant-aware models - Built-in Resolvers - Session and Header resolvers included
- Flexible Resolution - Implement your own tenant resolution strategy
- Middleware Support - HTTP middleware for tenant resolution with excluded routes
- Exception Handling - Throws exception when tenant cannot be resolved (translatable messages)
- Auto-assignment - Automatically sets tenant ID on model creation/update
- Zero Configuration - Works out of the box with sensible defaults
- Customizable - Override tenant column names per model
- Queue Support - Maintain tenant context in queued jobs
- Command Support - Run commands for specific tenants
- Laravel Octane Compatible - Uses scoped bindings for request isolation
- Validation Awareness -
existsanduniquerules can auto-scope by tenant - Tenant Timezone - Per-tenant/branch IANA zone from the JWT claim or the database, an instant cast, ISO-8601 serialization and a tzdata guard
Requirements
- PHP 8.2 or higher
- Laravel 10.x, 11.x, or 12.x
Installation
Install the package via Composer:
The package will auto-register its service provider and automatically publish the configuration file.
Quick Start
1. Configure (Optional)
The package uses ChainTenantResolver by default, which tries resolvers in order:
UserSessionTenantResolver- Getstenant_idfromgetSession()helperHeaderTenantResolver- Getstenant_idfromX-Tenant-IDheader
Configure the session helper in config/multi-tenant.php:
2. Add Trait to Models
Option A: Use HasTenant Trait Manually
Add the HasTenant trait to models that should be tenant-scoped:
Option B: Use Artisan Command (Recommended)
Configure your tables and run the command to automatically add the trait:
That's it! All queries on configured models will now be automatically scoped to the current tenant.
Configuration
The configuration file is automatically published to config/multi-tenant.php:
Database Migration
Add tenant_id column to your configured tables:
Query Listener
The package includes a database query listener that logs errors when queries are executed on tenant tables without a tenant_id filter.
Configuration
Smart Detection
The query listener is smart about detecting safe queries:
- Primary Key Operations: UPDATE/DELETE by
idoruuidare considered safe (model was already loaded with tenant scope) - Excluded Models: Models with
$withoutTenantScope = trueare skipped - Configurable Primary Keys: Add custom primary key columns to
primary_keysconfig
Log Output
When a query without tenant filter is detected:
Usage
Tenant Context
Access the current tenant ID anywhere in your application:
Model Trait
The trait provides:
- Automatic global scope for tenant filtering
- Automatic tenant ID assignment on create/update
tenant()relationship methodscopeForTenant($query, $tenantId)scope
Validation Rules (exists / unique)
Database-backed validation rules are tenant-aware by default when tenant context is available.
With this, checks are automatically scoped to the current tenant by adding
tenant_id = current_tenant_id to the validation query.
Scoped table names are taken from multi-tenant.tables, so you only configure
the table list once.
You can configure this behavior in config/multi-tenant.php:
Middleware
Register and use the tenant middleware:
Excluded Routes
Configure routes that should bypass tenant resolution using path patterns:
Production App Prefix:
If your application runs behind a reverse proxy or has a production-specific URL prefix, you can configure it to be automatically prepended to all excluded routes:
With this configuration, the excluded routes will become api/v1/health and api/v1/login.
Pattern Syntax:
- Use
*(asterisk) as wildcard to match any single path segment api/*/*/usersmatchesapi/v1/ar/users,api/v2/en/users, etc.webhook/*matcheswebhook/ottu,webhook/stripe, etc.- Leading slashes are automatically trimmed
Exception Handling
When no resolver can determine the tenant ID, a TenantNotResolvedException is thrown. This ensures all non-excluded routes have a valid tenant context.
Header Tenant Resolver
For API routes where the tenant ID is passed as a header (e.g., external integrations, webhooks):
Then send requests with the header:
Queued Jobs
For jobs that need tenant context, set the tenant ID in the job:
Event/Message Listeners
For listeners that receive messages with tenant context, use the SetsTenantFromPayload trait:
Automatically Add Trait to Listeners
Use the artisan command to add SetsTenantFromPayload trait to all listeners in a config file:
The command supports various config file formats:
- SQS events style:
'event.type' => ListenerClass::class - EventServiceProvider style:
['Event' => [ListenerClass::class]] - Simple array:
[ListenerClass::class, ...]
Configure the listener fallback behavior in config/multi-tenant.php:
The trait works with both array and object payloads:
- First checks if
tenant_idexists in the payload - If not found and
fallback_to_databaseis true, queries tenant table whereis_active = true - If fallback is disabled or no active tenant found, throws
TenantNotFoundException
Artisan Commands
Run commands for specific tenants:
Tenant Timezone
Every tenant (and optionally every branch) has an IANA timezone (Africa/Cairo, never an offset).
IAM mints it into the JWT as a timezone claim and stores it in the shared tenants.timezone /
branches.timezone columns. This package resolves it anywhere:
current() reads the session helper (multi-tenant.session.helper) for the timezone attribute,
so each service must copy the claim onto its session object:
In console (queue workers, cron) the session is skipped, exactly like tenant resolution: current()
then uses the tenant set on TenantContext (jobs that call setTenantId() / SetsTenantFromPayload).
Cron code that iterates tenants must call for() per tenant.
Instant columns (moments in time, stored as naive timestamps in app.timezone) use the
UtcDateTime cast. Reading is identical to Laravel's datetime cast; writing converts to the storage
zone first, so a Carbon assigned in another zone or a client string with an offset keeps its instant
(Laravel's datetime cast silently drops the zone):
Wall-clock values (timetable from/to, scheduled_time, HH:mm, birthdates, academic-year
bounds) are never converted: leave them as plain strings or date:Y-m-d / datetime:H:i casts.
Serialization: add SerializesDatesAsIso to your base model so every date attribute goes out as
ISO-8601 with an offset (2026-09-13T07:00:00+00:00), which is correct whatever the service's
app.timezone is. Because Laravel routes plain date casts through the same serializer, date-only
columns must use date:Y-m-d (see above).
Container guard: PHP bundles its own timezone table, and builds older than 2023 do not know that Egypt reinstated daylight saving time. Run the check in every entrypoint before the process manager:
Config (multi-tenant.timezone.*): default (fallback zone, null → app.timezone), column,
tenants_table, branches_table, session_attribute, session_branch_attribute.
API Reference
TenantContext
| Method | Description |
|---|---|
getTenantId(): ?int |
Get the current tenant ID |
hasTenant(): bool |
Check if a tenant is set |
setTenantId(?int $tenantId): void |
Manually set the tenant ID |
clear(): void |
Clear the tenant context |
runForTenant(int $tenantId, callable $callback): mixed |
Run callback with specific tenant |
HasTenant Trait
| Method | Description |
|---|---|
tenant(): BelongsTo |
Relationship to tenant model |
scopeForTenant($query, int $id): Builder |
Scope to specific tenant |
getTenantColumn(): string |
Get tenant column name (override) |
TenantTimezone
| Method | Description |
|---|---|
current(): string |
Zone of the current request's tenant/branch (session claim → tenant row → default) |
for(?int $tenantId, ?string $branchUuid = null): string |
Zone of a tenant/branch from the database (memoized per request/job) |
parse(mixed $value, ?string $timezone = null): ?Carbon |
Parse an incoming instant; naive input is read in the tenant zone; result in the storage zone |
set(?string $timezone): void |
Override the current zone for the rest of the request/job |
runIn(string $timezone, callable $callback): mixed |
Run callback with a specific current zone |
storage(): string |
Zone naive database values are stored in (app.timezone) |
isValid(mixed $timezone): bool |
Whether the value is an IANA zone name (offsets and Etc/GMT±n are rejected) |
ALL_BRANCHES |
'*' — branch claim meaning "all branches" (use the tenant zone) |
Carbon Macro
| Method | Description |
|---|---|
$date->inTenantTz(?string $timezone = null): static |
Copy of the date in the current (or given) tenant zone |
UtcDateTime Cast / SerializesDatesAsIso Trait
| Item | Description |
|---|---|
UtcDateTime::class |
Cast for instant columns: reads like datetime, writes via TenantTimezone::parse() |
SerializesDatesAsIso |
Model trait: serializeDate() → ISO-8601 with offset |
Translations
The package supports translatable exception messages. Language files are automatically published when the package is installed.
Supported languages: English (en), Arabic (ar)
To manually re-publish or update the language files:
Published files location: lang/vendor/multi-tenant/
Adding More Languages
Create additional language files in lang/vendor/multi-tenant/{locale}/exceptions.php:
SetsTenantFromPayload Trait
| Method | Description |
|---|---|
setTenantFromPayload(array\|object $payload): void |
Set tenant context from payload, throws TenantNotFoundException if not found |
Testing
Contributing
Please see CONTRIBUTING.md for details.
Changelog
Please see CHANGELOG.md for version history.
License
The MIT License (MIT). Please see LICENSE for more information.
Credits
All versions of multi-tenant with dependencies
illuminate/support Version ^10.0|^11.0|^12.0
illuminate/database Version ^10.0|^11.0|^12.0
illuminate/http Version ^10.0|^11.0|^12.0
nesbot/carbon Version ^2.62|^3.0