Queues, Cache, Storage, Events & Testing
Database isolation is only half of safe multi-tenancy — background jobs, caches, file storage, structured logs, and tests must stay isolated too. laravel-tenanted wires directly into laravel-rust's native subsystems for all five.
Background Queue Jobs (TenantQueueMiddleware)
Because laravel-tenanted writes the active tenant to laravel::context (tenant = "acme"), laravel::queue automatically serializes the tenant into every dispatched job payload — including chains, batches, retries, and failed hooks.
Add TenantQueueMiddleware to any tenanted job's middleware method:
use laravel::queue::{IntoMiddleware, Queueable, job};
use laravel_tenanted::TenantQueueMiddleware;
#[derive(Queueable)]
pub struct SendInvoiceReceipt {
pub invoice_id: i64,
}
#[job(tries = 3)]
impl SendInvoiceReceipt {
fn middleware(&self) -> impl IntoMiddleware {
// Fails closed with `TenantedError::NoTenant` if dispatched outside a tenant scope!
TenantQueueMiddleware::required()
}
async fn handle(self) -> laravel::Result<()> {
// 100% vanilla laravel-rust — automatically queries the dispatching tenant's DB!
let invoice = Invoice::find_or_fail(self.invoice_id).await?;
tracing::info!(invoice_id = invoice.id, "sent receipt");
Ok(())
}
}- Dispatching
SendInvoiceReceipt { invoice_id: 1 }.dispatch().await?from anacmeHTTP request automatically runshandle()insideacme's database, cache, and log scope. - Dispatching it outside any tenant scope fails closed immediately with
TenantedError::NoTenant. - For jobs that may run either inside a tenant or centrally, use
TenantQueueMiddleware::optional().
Structured Logging (laravel::context)
Every log line written inside a tenant request, using_tenant(...) block, or TenantQueueMiddleware job automatically carries tenant = "<id>" via laravel::context.
Customize the context key if desired:
TenantConfig::new("...").context_key("workspace")When the tenant scope exits (normally, via ?, or via future cancellation), an RAII guard restores the previous context value so tenant tags never bleed between requests or nested scopes.
Tenant-Scoped Caching
Sharing one cache namespace across tenants is one of the most common sources of production data leaks. laravel-tenanted gives you two fail-closed ways to isolate cache keys and atomic locks:
Option A: Native "tenanted" Cache Driver (Auto-Wired by .with_tenancy())
When you use .with_tenancy() or .with_tenancy_using(...), laravel-tenanted automatically registers the "tenanted" cache driver and sets it as your default cache store!
Now vanilla laravel::cache::get / put / forget / flush / lock automatically:
- Prefix every cache key with
tenant:{id}:and every atomic lock withtenant:{id}:lock: - Isolate
laravel::cache::flush()strictly to the active tenant (without wiping other tenants or breaking active atomic locks!) - Invalidate all cached keys & locks for a tenant automatically on
TenantManager::delete(...)so recreated tenant slugs never resurrect stale data - Fail closed with
TenantedError::NoTenantif called outside a tenant scope
To allow non-tenant cache calls under a central: prefix (or keep your existing default cache store):
use laravel_tenanted::WithTenancy;
laravel::Application::configure()
.with_tenancy_using(|t| {
t.allow_untenanted_cache(); // or `t.keep_default_cache()`
})Option B: Wrapping Any Existing Store (Redis, Database, Memory)
If your app already uses Redis or a database cache store, wrap it on demand with laravel_tenanted::cache(), laravel_tenanted::cache_store("redis"), or tenants.cache_store("redis") (on Inject<TenantManager>, which also shares automatic delete() invalidation):
use laravel::time::ToSpan;
// Prefixes with `tenant:{current}:dashboard`; fails with `NoTenant` outside a tenant!
laravel_tenanted::cache()?.put("dashboard", payload, 5.minutes()).await?;
let cached: Option<Dashboard> = laravel_tenanted::cache()?.get("dashboard").await?;
// Or target a named Redis store explicitly (with `delete()` epoch invalidation):
tenants.cache_store("redis")?.put("dashboard", payload, 5.minutes()).await?;Tenant-Scoped File Storage (TenantedStorage)
Prevent cross-tenant file leaks on local disks, S3, Cloudflare R2, or Laravel Cloud disks with laravel_tenanted::storage() and laravel_tenanted::storage_disk("s3"):
// Wraps the default `laravel::storage::Disk` scoped to `tenants/{current}/`:
let disk = laravel_tenanted::storage()?;
disk.put("invoices/inv-001.pdf", pdf_bytes).await?;
// Or target any named disk (`"s3"`, `"public"`, `"local"`, `"laravel_cloud"`):
let s3 = laravel_tenanted::storage_disk("s3")?;
let bytes = s3.get("avatars/avatar.png").await?;
// Listings automatically strip `tenants/{current}/` so paths stay clean & tenant-relative:
let files = s3.all_files("").await?; // e.g. ["avatars/avatar.png"]
// Path traversal (`..`, `\`, null bytes) is strictly rejected!
assert!(s3.get("../globex/avatars/avatar.png").await.is_err());Opt into automatic file cleanup when a tenant is deleted (GDPR offboarding):
laravel::Application::configure()
.with_tenancy_using(|t| {
t.storage_prefix("tenants") // default: `tenants/{id}/...`
.cleanup_storage_disk("s3") // deletes `tenants/{id}` on `delete()`
.cleanup_storage_disk("local");
})Calling laravel_tenanted::storage() outside a tenant scope fails closed with TenantedError::NoTenant.
Lifecycle Events
laravel-tenanted dispatches six native laravel::event structs — all marked #[event(at_dispatch)] so listeners fire immediately even while a database transaction is open:
| Event | Fields | Fired When |
|---|---|---|
TenantEntered | tenant, connection | Entering using_tenant / ResolveTenantMiddleware |
TenantExited | tenant | Leaving a tenant scope |
TenantCreated | tenant, connection | create(...) / tenant:create finishes provisioning |
TenantMigrated | tenant, applied: Vec<String> | One or more migrations finish applying |
TenantEvicted | tenant | An open pool is evicted by the LRU cap |
TenantDeleted | tenant | delete(...) / tenant:delete removes a tenant |
Register listeners with standard laravel-rust .with_events(...):
use laravel::event::Event;
use laravel_tenanted::TenantCreated;
laravel::Application::configure()
.with_events(|events, _| {
events.listen(|ev: Event<TenantCreated>| async move {
tracing::info!(tenant = %ev.tenant, "provisioning welcome seed data");
});
})Testing Multi-Tenant Applications
Because TenantedServiceProvider binds TenantManager as a per-Application DI singleton (never relying on shared global state), parallel #[tokio::test] tests stay 100% isolated from each other.
Use the built-in RAII laravel_tenanted::testing::TempTenants helper to spin up an isolated temporary directory of tenant SQLite databases that cleans itself up automatically on drop:
use laravel::config::Env;
use laravel::testing::MakesHttpRequests;
use laravel_tenanted::{WithTenancy, testing::TempTenants};
#[tokio::test]
async fn tenants_cannot_see_each_others_invoices() {
let temp = TempTenants::new();
let app = laravel::Application::configure()
.replace_env(Env::default())
.with_tenancy_using(|t| {
t.database(temp.config().url_template)
.header("x-tenant-id")
.create_table("invoices", |table| {
table.id();
table.string("label");
table.big_integer("cents");
});
})
.with_routing(|routing, _| {
// ... your app routes ...
})
.create();
app.post("/invoices")
.header("x-tenant-id", "acme")
.header("accept", "application/json")
.json(serde_json::json!({ "label": "INV-1", "cents": 5000 }))
.await
.assert_ok();
// Globex cannot see Acme's invoice #1 (404 Not Found):
app.get("/invoices/1")
.header("x-tenant-id", "globex")
.header("accept", "application/json")
.await
.assert_status(404);
}