Skip to main content

Crate laravel_tenanted

Crate laravel_tenanted 

Source
Expand description

Storage-agnostic database-per-tenant support for laravel-rust — the idiomatic Rust equivalent of Rails’ activerecord-tenanted, with zero dependency on LiteVault.

Built natively on laravel::db::DatabaseManager, DatabaseManager::using_connection, laravel::context, laravel::queue::Middleware, laravel::cache::Store, laravel::storage, laravel::event, laravel::errors::Status, and Artisan commands so completely ordinary laravel-rust code (#[model], create!(...), db::table(...), db::query!(...), db::transaction(...), Route Model Binding, DB validation, queues, cache, file storage, and logs) is automatically tenant-scoped across:

  • Plain local SQLite (sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc, default),
  • PostgreSQL / MySQL (postgres://user:pass@host/tenant_{tenant}), or
  • LiteVault S3/R2 SQLite VFS (laravel_rust_litevault::tenanted_database_url("tenants/{tenant}/main")).

§Quick Start

Enable multi-tenancy in 1 line on Application::configure():

ⓘ
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy()
    .with_routing(|routing, _| {
        routing.routes(|route| {
            route.get("/invoices", list_invoices);
        });
    })
    .run()

Or customize your subdomain / session resolver and tenant tables inline with .with_tenancy_using(|t| ...) (no Box::pin, no manual provider/cache wiring):

ⓘ
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy_using(|t| {
        t.subdomain("myapp.com") // or t.session("active_org") for Inertia apps
            .create_table("invoices", |table| {
                table.id();
                table.string("label").unique();
                table.big_integer("cents");
            });
    })
    .with_routing(|routing, _| {
        routing.routes(|route| {
            route.get("/invoices", list_invoices);
        });
    })
    .run()

Inside any route, job, or using_tenant scope, write completely normal laravel-rust code:

ⓘ
use laravel::http::Json;
use laravel::model::model;
use laravel_tenanted::Tenant;

#[model]
pub struct Invoice { pub id: i64, pub label: String, pub cents: i64 }

async fn list_invoices(_tenant: Tenant) -> laravel::Result<Json<Vec<Invoice>>> {
    Ok(Json(Invoice::query().get().await?))
}

Re-exports§

pub use builder::TenancyBuilder;
pub use builder::WithTenancy;
pub use cache::TenantedCache;
pub use cache::TenantedCacheSettings;
pub use cache::TenantedCacheStore;
pub use commands::TenantCreateCommand;
pub use commands::TenantDeleteCommand;
pub use commands::TenantEvictCommand;
pub use commands::TenantListCommand;
pub use commands::TenantMigrateCommand;
pub use config::IntoTenantMigration;
pub use config::MigrationFn;
pub use config::MigrationFuture;
pub use config::TenantConfig;
pub use config::TenantDeleteFn;
pub use config::TenantExistsFn;
pub use config::TenantListerFn;
pub use config::TenantMigration;
pub use config::TenantPoolStats;
pub use error::NO_TENANT_CONNECTION;
pub use error::TenantedError;
pub use error::sanitize_tenant_id;
pub use events::TenantCreated;
pub use events::TenantDeleted;
pub use events::TenantEntered;
pub use events::TenantEvicted;
pub use events::TenantExited;
pub use events::TenantMigrated;
pub use extract::Tenant;
pub use manager::TenantManager;
pub use manager::global_manager;
pub use manager::set_global_manager;
pub use middleware::RequestTenantResolver;
pub use middleware::ResolveTenantMiddleware;
pub use provider::TenantedServiceProvider;
pub use queue::TenantQueueMiddleware;
pub use storage::TenantedStorage;

Modules§

builder
One-line, Taylor-Otwell-style automagic registration on laravel::foundation::ApplicationBuilder.
cache
Tenant-isolated caching for laravel-rust:
commands
Native laravel-rust Artisan commands automatically registered by crate::TenantedServiceProvider:
config
Configuration, schema/SQL migration definitions, and pool statistics for laravel-tenanted.
error
Typed error hierarchy for laravel-tenanted, modeled after Rails’ ActiveRecord::Tenanted errors and laravel-rust’s native #[derive(Status)].
events
Native laravel::event::Event lifecycle events dispatched as tenants are entered, exited, created, migrated, evicted, and deleted.
extract
First-class laravel-rust HTTP route extractor for the active tenant, mirroring laravel::auth::Authenticated and laravel::http::RequestId.
manager
Core TenantManager built natively on laravel::db::DatabaseManager, DatabaseManager::using_connection, laravel::context, and laravel::event.
middleware
First-class laravel::http::Middleware resolving a customer’s tenant per HTTP request and running the entire request inside crate::TenantManager::run.
provider
Drop-in laravel-rust TenantedServiceProvider that wires database-per-tenant support into the application’s DI container, HTTP middleware pipeline, cache drivers, and Artisan CLI.
queue
Native laravel::queue::Middleware that automatically restores the dispatching tenant’s database, cache, and log scope inside background queue workers!
storage
Tenant-isolated file storage wrapping any laravel::storage::Disk ("local", "public", "s3", "laravel_cloud", or "read_through").
testing
Ergonomic test helpers for isolated multi-tenant laravel-rust tests.

Functions§

cache
Return a tenant-scoped cache wrapper around the application’s default cache store. Fails closed with TenantedError::NoTenant if no tenant is active.
cache_store
Return a tenant-scoped cache wrapper around a named laravel::cache store (e.g. "redis").
central
Alias for without_tenant familiar to stancl/tenancy users.
connection
Obtain the native laravel::db::AnyConnection for the currently active tenant (or fail with TenantedError::NoTenant).
connection_name
Return the DatabaseManager connection name for the active tenant (e.g. "tenant_acme").
create
Explicitly provision and migrate a new tenant database.
current
Return the validated tenant ID active in the current scope (or None when outside a tenant scope or inside without_tenant).
current_connection_name
Backwards-compatible alias for connection_name.
current_tenant
Backwards-compatible alias for current.
delete
Evict and permanently delete a tenant database.
evict
Evict one tenant’s connection pool from the LRU cache.
exists
Check whether tenant_id already exists.
for_each
Iterate across all discovered tenants (or an explicit list via for_each_in), executing f inside run for each tenant.
for_each_in
Iterate across an explicit list of tenant IDs, executing f inside run for each.
id
Return the currently active tenant ID as a typed Result<String, TenantedError>.
is_active
Return true when code is executing inside an active tenant scope.
landlord
Alias for without_tenant familiar to spatie/laravel-multitenancy users.
list
List all discovered and currently open tenants.
manager
Resolve the active TenantManager from the current laravel::Application container (or fallback global manager).
migrate
Run pending migrations on tenant_id.
require
Return the currently active tenant ID, or fail with TenantedError::NoTenant.
run
Run an async block strictly scoped to one validated tenant — exact Rust equivalent of Rails’ ApplicationRecord.with_tenant("acme") { ... }.
storage
Return a tenant-scoped storage wrapper around the application’s default laravel::storage::Disk (automatically prefixing all paths with {storage_prefix}/{id}/ and rejecting path traversal). Fails closed with TenantedError::NoTenant if no tenant is active.
storage_disk
Return a tenant-scoped storage wrapper around a named laravel::storage::Disk (e.g. "s3", "public", "local", or "laravel_cloud"), automatically prefixing all paths with {storage_prefix}/{id}/ and rejecting path traversal.
table
Start a native laravel::db::Builder scoped to the currently active tenant’s database.
using_tenant
Alias for run matching laravel::db::using_connection.
with_tenant
Alias for run matching Rails’ with_tenant.
without_tenant
Temporarily execute fut outside any tenant scope on the central (shared) database — exact sibling of laravel::model::without_events and Rails’ without_tenant. Restores the surrounding tenant scope cleanly on exit.