Skip to main content

Multi-tenant SaaS

Every tenant wants to name a document getting-started, and no tenant may reach another's rows through a guessed URL. Those are two different problems, and each needs its own hook.

#[Polyslug(source: 'title', scope: 'tenant_id')] // 'hello' may repeat across tenants
class Doc extends Model implements Sluggable
{
use HasPolyslug;

public function polyslugResolveQuery(Builder $query): Builder
{
return $query->where('tenant_id', tenant()->id); // a slug resolves only within the tenant
}
}
  • scope: 'tenant_id' makes uniqueness per tenant, so two tenants can both own getting-started without a -2 suffix appearing for the second one.
  • polyslugResolveQuery() is the isolation contract. Without it, a URL from tenant A still resolves inside tenant B's session — the scope only decided who may own the slug, never who may reach it. A row outside the gate returns a 404 indistinguishable from a nonexistent one, so it is not an existence oracle either.

Use both. Either one alone leaves a hole.

Adding per-tenant rules​

If tenants may define their own reserved words or their own encoder, implement ConfiguresPolyslug instead of the static attribute — it is resolved fresh on every use:

public function polyslug(): PolyslugConfig
{
return PolyslugConfig::fromAttribute(new Polyslug(
source: 'title',
scope: 'tenant_id',
reserved: tenant()->reservedSlugs(),
));
}

Deleting a tenant​

A tenant's rows are usually deleted by query, in chunks, because model events over millions of rows are not an option. A query fires no deleted event, so pass each chunk's keys to polyslugForget() as well:

Doc::query()->where('tenant_id', $tenant->id)->chunkById(1000, function ($docs): void {
$keys = $docs->modelKeys();

Doc::polyslugForget($keys);
Doc::query()->whereKey($keys)->delete();
});

The tenant's slug rows are deleted. Its short links and identity tokens no longer name its records, and their tokens stay taken, so a link the tenant shared never leads into another tenant's records. See deleting records with a query.

See also​