A multi-tenant Laravel SaaS serves many customer organizations from one codebase. Its architecture must keep every tenant from reading or changing another tenant's data.
Isolation is an end-to-end property spanning tenant resolution, authorization, queries, queues, cache, files, search, logs, exports, support access, and deletion. Any path that loses context can expose or mutate another customer’s data.
The examples below come from ClinicTek, the clinic management SaaS we build and run on Laravel and PostgreSQL. A tenant there is a clinic. In your product it might be a company, a branch or a workspace.
Tenants, users and one deployment
A multi-tenant SaaS application is one deployment of software that serves many customers, called tenants, while each tenant sees only its own data. A tenant is usually a customer organization, and one tenant has many users. Tenants and users are different things: ten staff accounts at one company are ten users and one tenant.
Laravel provides middleware, policies, queues and Eloquent query scopes. How you use them to keep tenants apart is a design decision, and the sections below show ours.
Multi-tenant vs single-tenant SaaS
In a single-tenant SaaS, each customer gets its own deployment of the application, and often its own database. In a multi-tenant SaaS, customers share one deployment and the software keeps their data apart. Multi-tenancy is usually cheaper to run. Single-tenant deployments suit customers whose isolation or compliance rules justify the extra cost.
| Multi-tenant | Single-tenant | |
|---|---|---|
| Infrastructure | One shared deployment | A dedicated deployment per customer |
| Cost per customer | Lower, because customers share infrastructure | Higher, because each deployment is paid for separately |
| Isolation | Enforced by your application and database rules | Enforced by separate infrastructure |
| Upgrades | One release reaches every customer, and so can a bad one | Rolled out customer by customer, with more work per release |
| Noisy neighbor | One heavy tenant can slow the others | Tenants are unlikely to affect each other's performance |
| Customer-specific needs | Settings and features per tenant inside one codebase | One customer's deployment can be adapted on its own |
You can also mix the two: shared deployments for most tenants and dedicated ones for the few that need them. ClinicTek is multi-tenant: every clinic shares one schema in one PostgreSQL database.
Diagram: one request through the tenant layers
The diagram follows one request through the layers that keep a tenant's data apart in ClinicTek. The two dashed boxes show what queue jobs rebuild and the prefix rule for cache keys, file paths and search indexes. The sections below cover each box.
- The browser asks for a clinic's page, such as an invoice.
- The application resolves the tenant from the host and fails if there is no match.
- A Laravel policy checks the user and the specific invoice.
- The query runs as the application database role, with the tenant ID set on the PostgreSQL session.
- Row-level security returns only that tenant's rows.
Queue jobs rebuild and clear the same context. Cache keys, file paths and search indexes need the same tenant prefix.
Choose a database model from constraints
A shared PostgreSQL schema stores tenants in the same tables and scopes rows by a tenant key. It can simplify migrations and operations for many products, but it makes query discipline and defence in depth critical. A database-per-tenant model strengthens some operational boundaries and can simplify individual restoration, while multiplying connections, migrations, monitoring targets, and backups. Hybrid approaches can isolate selected tenants or workloads.
Evaluate regulatory obligations, expected data size, cross-tenant reporting, restoration requirements, scaling patterns, and the team’s operational capacity. A database-per-tenant design is not safer if the team cannot patch and monitor every database consistently. A shared schema is not economical if weak isolation creates unacceptable risk.
| Criterion | Shared schema | Database per tenant | Hybrid |
|---|---|---|---|
| Migrations | One run changes every tenant | One run per database, with a list of databases still behind | Two paths to maintain |
| Isolation | Query discipline plus database policies | Stronger boundary between databases | Separate databases for large or sensitive tenants |
| Restoring one tenant | Restore to an isolated environment, extract, repair | Restore that database | Depends on where the tenant lives |
| Cross-tenant reporting | One query under a privileged role | Aggregation across databases | Both |
| Operating cost | One database to monitor and back up | Connections, backups and monitoring per tenant | In between |
ClinicTek uses a shared schema in one PostgreSQL database and enforces isolation twice. Eloquent models add the tenant condition to their queries automatically, and PostgreSQL row-level security hides or refuses any row outside the current tenant.
Resolve the tenant from a source the user cannot change
Resolve the tenant from the domain, the route or a verified membership. Never trust a tenant ID sent in a form or API body.
ClinicTek reads the request's host and finds the clinic by its subdomain, or by a custom domain in the domains table. It sets the tenant context before any business logic runs and passes the tenant ID to the PostgreSQL session. A tenant-required route with no context fails with an explicit error. The system never picks a default tenant.
Resolving the tenant does not authorize the action. Knowing a request belongs to clinic A does not prove the user may open invoice X inside it. Each action still needs a Laravel policy that checks the user and the record.
Let PostgreSQL enforce the boundary
Row-level security (RLS) makes PostgreSQL apply a condition to every query on a table from a role that RLS governs, whatever code sent it. It catches the raw query, join or report that forgot its tenant scope. Every ClinicTek tenant-data table gets four policies, one each for select, insert, update and delete:
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_select ON invoices
FOR SELECT USING (
NULLIF(current_setting('app.current_tenant_id', true), '') IS NOT NULL
AND tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::bigint
);
-- tenant_isolation_insert, _update and _delete follow the same comparison
An empty session value matches no rows.
Three rules from the PostgreSQL documentation decide how you set up roles. Table owners bypass policies unless the table uses FORCE ROW LEVEL SECURITY. Superusers and roles with BYPASSRLS always bypass them. A table with RLS enabled and no policy shows no rows to any role subject to RLS. So ClinicTek keeps these roles apart:
| Role | Used for | Guarantee |
|---|---|---|
| Owner | Migrations, tables and policies | Never used by the running app |
| Application | Web requests, queue workers, realtime | Subject to RLS; owns no table |
| Platform | Explicit cross-tenant admin work | Separate connection with BYPASSRLS; never a staff connection |
| RLS tester | Denial tests only | NOBYPASSRLS, so a passing test proves the policy denies |
ClinicTek used to have a session setting that let the application itself switch RLS off for admin work. In July 2026 we rewrote every tenant policy so none reads that setting, and moved cross-tenant admin work to the separate platform role. The old setting can still sit in a pooled session, but it grants nothing.
Carry tenant context into queues
A queued job runs after the request that created it has ended, usually in another process. When you pass an Eloquent model to a job, Laravel serializes only its identifier and re-retrieves the model when the job runs. It does so under whatever context the worker holds at that moment. Put the tenant ID in the job payload, rebuild the context when the job starts, and clear it when the job ends.
ClinicTek clears both the in-memory context and the PostgreSQL session value at every job boundary. A long-lived PHP worker therefore cannot carry one clinic's context into the next job.
One case tripped us up. With the sync queue driver, jobs run inside the request, and clearing the context after a nested job broke the request that was still running. The reset now restores the request's tenant when one is bound and clears only when none is. A dedicated test guards that behavior.
Namespace cache, files, search and realtime channels
Every cache key, lock, rate limit and feature flag that holds tenant data needs a tenant prefix. Without one, the cache can serve one tenant's result to another even when the database query is correct. Apply the same rule to file paths, signed URLs, search indexes and exports. Keep a list of every store that receives tenant data, such as Redis, object storage, search and email providers. Record how each one exports and deletes that data.
Realtime channels need authorization per subscription. In ClinicTek's release check on 9 July 2026, the server refused with a 403 when a user tried to subscribe to another clinic's live schedule. It accepted the same user's subscription to their own clinic's schedule.
Give support staff audited, time-limited access
Support access needs its own audited path, so nobody shares a staff password. In ClinicTek, a support operator must enter a reason of at least 20 characters and choose an active staff account in that same clinic. That opens a 60-minute support window and issues a one-time handoff token valid for five minutes. The token cannot be replayed or used for another clinic. Opening, starting, ending, revoking and automatic expiry each write an entry to the clinic's audit log.
Change a shared schema without downtime
In a shared schema, one migration changes every tenant's tables. Use the expand-and-contract pattern, which changes the schema in five safe steps:
- Add the new column or table in a form the current code ignores.
- Deploy code that handles both the old and the new shape.
- Backfill old rows in batches and watch lock times.
- Enforce the new constraint once the backfill is complete.
- Drop the old column in a later release.
Run migrations as the owner role only. If you see must be owner of table, the migration ran as the application role. That role must never alter tables, so PostgreSQL refused it.
Test isolation with two tenants
Every important test suite should prove that one tenant cannot reach another:
- Create two tenants with one user each.
- Sign in as the first tenant's user.
- Request a record of the second tenant by its direct ID: read, update, delete, export and file download.
- Expect 404. A 403 tells an attacker the record exists; Laravel policies offer
denyAsNotFound()for this. - Repeat the request as the second tenant's user and expect success, so you know the first request was denied for the right reason.
- Repeat the cases for jobs, cache, search and realtime channels.
ClinicTek adds a schema test that finds every table with a tenant_id column. It fails if any tenant-data table lacks the four policies or forced RLS. Platform tables that carry tenant_id but are not tenant-scoped sit on a written allowlist, each with its reason. The domains table is one of them, because the system reads it before it knows the tenant. The same file lists the tables tenants may only read and the platform-only tables that deny every tenant role.
In the release check of 9 July 2026, before the July policy rewrite, all 12 tests in the seven isolation suites the check ran passed. Our multi-tenant authorization testing guide covers these tests in depth.
Keep billing records separate
Billing in a multi-tenant SaaS needs seven separate records, each owned by one tenant or by the platform:
| Record | What it holds | Changed after creation? |
|---|---|---|
| Plan catalog | Plans, prices and included limits, with a version and an effective date | A new version is published; old ones stay |
| Subscription | The tenant's agreement: plan, price version, period, state | State changes; agreed terms stay as agreed |
| Entitlement | What the product allows: seats, branches, features | Follows the subscription and any temporary grant |
| Invoice | Lines, quantities, discount, tax, currency, total | Voided or corrected by a new document; the total is never edited |
| Payment attempt | Provider, amount, state, provider reference, idempotency key | New attempts are added; old ones are kept |
| Provider event | The provider's event ID and how it was processed | Stored once |
| Reconciliation adjustment | The difference, its reason and who approved it | Added, never deleted |
Price changes should not rewrite agreements. ClinicTek keeps every price and included limit in one versioned, approved pricing file. It generates the plan tables from that file, so editing a plan row changes no price.
When we changed the staff seats included in the ClinicTek plan, a subscription bought before the change kept its seat terms until renewal. Every existing staff account stayed active. A renewal reads the coupon terms frozen on the purchase invoice, never the live coupon.
Payment attempts are separate from invoices. One invoice can see a failed attempt, a success, a partial payment or a refund, each with its own reference. Clinics pay their ClinicTek subscription today by CliQ, Jordan's instant payment system, and upload proof of payment, which moves from submitted to verified or rejected.
A coupon is redeemed exactly once at verification, and released if the checkout is rejected or expires. Every checkout, payment intent and plan or seat change carries an idempotency key. This unique token lets the system ignore a repeat, so a resubmitted request cannot run twice.
Provider callbacks arrive late, twice or out of order. Stripe's webhook documentation says endpoints "might occasionally receive the same event more than once" and that delivery order is not guaranteed. It also asks you to return a 2xx status before any complex logic and to verify the signature on the raw body. Store the provider's event ID, skip events you have already processed, and queue the work.
ClinicTek's subscription webhook receiver passes every inbound event through one ledger that prevents double processing. The ledger sits outside tenant data because a callback arrives before the system knows which clinic it belongs to. The receiver stays off until we connect an automated payment provider.
Price increases need notice on record. ClinicTek's contract promises 30 days' notice of a price change, and the renewal invoice records the rule that set its amount. We recommend that a renewal charge the current price when the notice was late. We also recommend that a price cut take effect at any time. ClinicTek's notices are built as append-only rows, numbered within each renewal, and are not switched on yet.
Reconcile against each tenant's own agreement. ClinicTek compares what each clinic paid with the expected price for its own agreement: its locked rate or the invoice that started its period. Repricing at today's catalog prices would flag a false difference every time an offer changes. Fix a real difference with an adjustment that records its reason and approver, and leave the issued invoice as it is.
Test time and money as inputs. ClinicTek stores amounts as integer fils (1 JOD is 1,000 fils) and writes every date-time in that pricing file with Amman's UTC offset. Every period includes its start and excludes its end.
The test suite pins the pricing clock to 11 October 2026, 12:00 Amman time, so no result flips with the calendar. Each test moves the clock where it needs it. Copy these cases into your own suite:
| Case | Expected result |
|---|---|
| Upgrade mid-period | A prorated invoice that charges only the days left in the period; the new entitlement applies at once |
| Downgrade | Applies at renewal; current entitlement stays to period end |
| Duplicate payment callback | One recorded payment |
| Callback for an invoice you have not created yet | Quarantined for review |
| Partial refund | Invoice balance derived from events; access follows policy |
| Period ending at midnight local time | No day counted twice or lost |
| Leap year | Correct period length in proration |
| One tenant's billing admin requests another tenant's invoice | Denied |
Migrate billing in shadow first. ClinicTek's new revenue ledger is built to run in shadow mode. It computes results beside the current path and stores comparison evidence tagged with the release. Finance and operations must review evidence from two releases before it replaces the current path. It is not switched on in production yet.
When you migrate from another system, import current terms, periods, open invoices, credits and provider references. Keep an old-to-new ID map, and never trigger a charge because a record was imported.
Back up, export and delete per tenant
Backups restore service; tenant exports give a customer usable data. In a shared schema, restoring one tenant means restoring to an isolated environment, extracting and validating that tenant's records, and applying a controlled repair. Deletion must reach tables, files, search indexes and queued work, and your retention policy should state honestly how long data lives on in backups. When a clinic cancels ClinicTek, it gets a full export of its data within 7 business days, followed by permanent deletion.
Checklist
- [ ] Every tenant-required route fails when context is missing.
- [ ] No tenant ID is read from a request body.
- [ ] Every tenant-data table has RLS enabled and forced, with policies for all four commands.
- [ ] The application's database role owns no table, is not a superuser and lacks
BYPASSRLS. - [ ] Every job rebuilds tenant context on start and clears it on exit.
- [ ] Every cache key, lock and file path carries the tenant ID.
- [ ] Every realtime channel checks tenant membership.
- [ ] Support access needs a written reason, expires, and is audited.
- [ ] A two-tenant test denies read, update, delete and export across tenants.
- [ ] A schema test catches any new tenant table without policies.
- [ ] Billing records are append-only where the table above says so.
Get your tenant isolation reviewed
We can build your multi-tenant platform on these layers through our SaaS platform development service. If your platform is close to launch, our pre-launch architecture and security review starts at JOD 600. No sales tax is added. Request it on our legacy modernization and architecture review page, describe your platform in our project form, or message us with the WhatsApp button on this page. The ClinicTek case study shows the same boundaries from the clinic's side.
Every ClinicTek detail in this post comes from the product's code, tests, documentation and release reports as of November 2026.
Last updated: 4 November 2026. Billing section absorbed from the merged billing guide.




