Inertia + React Starter Kit: Org Switcher & Super-Admin Tenancy
If you're building with the laravel-rust + Inertia React starter kit (laravel-rust-shadcn), you can add full database-per-tenant multi-tenancy — complete with a sidebar Organization Switcher and Super-Admin org switching — in minutes using laravel-tenanted's built-in .session("active_org") resolver.
Architecture Overview
- Central Database (
#[model(connection = "central")]):User,Organization, andOrganizationMembershiplive in the shared central database so authentication (auth.session::<model::Users<User>>()) works seamlessly across every organization. - Tenant Databases (default
#[model]): Every business model (Invoice,Project,Customer, etc.) has zero tenant columns and zero tenancy boilerplate — each organization gets its own physical database (tenants/{slug}/main.sqlite3ortenant_{slug}on Postgres/MySQL). - Signed Session Resolution (
t.session("active_org")):laravel-tenantedattachesResolveTenantMiddlewareto thewebmiddleware group (running right afterStartSession) and readsactive_orgfrom the encrypted Laravel session cookie. Public routes (/login,/register,/organizations/switch) pass through untenanted, while every org route fails closed withTenant/require_tenant().
1. Enable Session Tenancy in src/app.rs
Add .with_tenancy_using(...) directly on Application::configure() in src/app.rs:
use laravel::foundation::ApplicationBuilder;
use laravel::{Application, inertia, model};
use laravel_tenanted::WithTenancy;
use crate::http::middleware::HandleInertiaRequests;
use crate::models::User;
use crate::routes;
pub fn configure() -> ApplicationBuilder {
Application::configure()
.with_migrations(laravel::db::migrations!("database/migrations"))
.with_schema(laravel::db::schema!("database/schema"))
.with_auth(|auth, _| {
auth.session::<model::Users<User>>();
})
.with_tenancy_using(|t| {
t.session("active_org")
.central_connection("central")
.auto_create(false)
.allow_untenanted_cache() // lets /login rate limiting run outside a tenant scope
.cleanup_storage_disk("local")
.create_table("projects", |table| {
table.id();
table.string("name");
table.string("status").default("active");
table.timestamps();
});
})
.with_routing(|routing, _| {
routing
.web(routes::web::routes)
.api(routes::api::routes)
.health("/up");
})
.with_middleware(|middleware, _| {
middleware.web(|web| {
web.append(inertia::middleware(HandleInertiaRequests));
});
})
}2. Central Models (User, Organization, OrganizationMembership)
Pin authentication & organization directory models to "central" so they work both inside and outside an active organization:
use laravel::model::model;
#[model(connection = "central")]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
pub is_super_admin: bool,
}
#[model(connection = "central")]
pub struct Organization {
pub id: i64,
pub slug: String, // e.g. "acme", "globex" — validated by `sanitize_tenant_id`
pub name: String,
}
#[model(connection = "central")]
pub struct OrganizationMembership {
pub id: i64,
pub user_id: i64,
pub organization_id: i64,
pub role: String, // "owner" | "admin" | "member"
}3. Share Active Org & Switchable Orgs in HandleInertiaRequests
Update src/http/middleware/handle_inertia_requests.rs so every Inertia page automatically receives the active org and the list of orgs the current user can switch into (including all orgs when user.is_super_admin is true!):
use laravel::inertia::{self, Props, props};
use laravel::prelude::*;
use serde_json::json;
use crate::models::{Organization, OrganizationMembership, User};
pub struct HandleInertiaRequests;
impl inertia::Middleware for HandleInertiaRequests {
async fn share(&self, request: &Request) -> laravel::Result<Props> {
let user: Option<User> = request.user().await?;
let active_slug = laravel_tenanted::current();
let organizations: Vec<Organization> = match &user {
Some(u) if u.is_super_admin => {
// Super-admins can inspect and switch into any provisioned organization:
Organization::query().order_by(Organization::name).get().await?
}
Some(u) => {
let org_ids: Vec<i64> = OrganizationMembership::query()
.filter(OrganizationMembership::user_id.eq(u.id))
.get()
.await?
.into_iter()
.map(|m| m.organization_id)
.collect();
if org_ids.is_empty() {
Vec::new()
} else {
Organization::query()
.filter(Organization::id.is_in(org_ids))
.order_by(Organization::name)
.get()
.await?
}
}
None => Vec::new(),
};
Ok(props! {
name => laravel::config().app.name.clone(),
auth => json!({ "user": user }),
tenancy => json!({
"current_org": active_slug,
"organizations": organizations,
"is_super_admin": user.as_ref().is_some_and(|u| u.is_super_admin),
}),
status => request.session().ok().and_then(|s| s.get::<String>("status")),
})
}
fn error_page(&self) -> Option<&str> {
Some("Error")
}
}4. Org Switcher & Provisioning Routes
Add two authenticated web routes — one to switch orgs (checking membership OR is_super_admin) and one to create & provision a brand-new organization database:
use laravel::auth::Authenticated;
use laravel::http::{Redirect, StatusCode};
use laravel::model::create;
use laravel::session::Session;
use laravel::validation::Valid;
#[laravel::input]
#[validate(anyone)]
pub struct SwitchOrgInput {
#[validate(required)]
pub slug: String,
}
pub async fn switch_organization(
auth: Authenticated<User>,
session: Session,
Valid(input): Valid<SwitchOrgInput>,
) -> laravel::Result<Redirect> {
let clean_slug = laravel_tenanted::sanitize_tenant_id(&input.slug)?;
let org = Organization::query()
.filter(Organization::slug.eq(&clean_slug))
.first()
.await?
.ok_or_else(|| laravel::Error::status(StatusCode::NOT_FOUND, "Organization not found"))?;
// Authorize: either a member of `org` OR a platform super-admin!
if !auth.is_super_admin {
let is_member = OrganizationMembership::query()
.filter(OrganizationMembership::user_id.eq(auth.id))
.filter(OrganizationMembership::organization_id.eq(org.id))
.exists()
.await?;
if !is_member {
return Err(laravel::Error::status(
StatusCode::FORBIDDEN,
"You do not belong to this organization",
));
}
}
session.put("active_org", &org.slug);
Ok(Redirect::to("/dashboard"))
}
pub async fn create_organization(
auth: Authenticated<User>,
session: Session,
Valid(input): Valid<SwitchOrgInput>,
) -> laravel::Result<Redirect> {
let clean_slug = laravel_tenanted::sanitize_tenant_id(&input.slug)?;
// 1. Provision & migrate the physical tenant database:
laravel_tenanted::create(&clean_slug).await?;
// 2. Record the organization + owner membership in the central DB:
let org = create!(Organization {
slug: clean_slug.clone(),
name: input.slug.clone(),
})
.await?;
create!(OrganizationMembership {
user_id: auth.id,
organization_id: org.id,
role: "owner",
})
.await?;
// 3. Switch the user straight into their new organization:
session.put("active_org", &org.slug);
Ok(Redirect::to("/dashboard"))
}And inside your tenant routes (like DashboardController), write 100% vanilla laravel-rust code:
use laravel::inertia::{Inertia, props};
use laravel_tenanted::Tenant;
pub async fn dashboard(tenant: Tenant) -> laravel::Result<impl IntoResponse> {
let projects = Project::query().get().await?; // automatically queries active org's DB!
let files = laravel_tenanted::storage()?.all_files("").await?; // tenants/{org}/...
Ok(Inertia::render("Dashboard", props! {
org => tenant.into_inner(),
projects => projects,
files => files,
}))
}5. Sidebar <OrgSwitcher /> Component (AppLayout.tsx)
Drop this right into <SidebarHeader> or <SidebarFooter> in resources/js/layouts/AppLayout.tsx:
import { router, usePage } from '@inertiajs/react';
import { Building2Icon, CheckIcon, ChevronsUpDownIcon, ShieldIcon } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { SidebarMenuButton } from '@/components/ui/sidebar';
type Org = { id: number; slug: string; name: string };
export function OrgSwitcher() {
const { tenancy } = usePage<{
tenancy: { current_org: string | null; organizations: Org[]; is_super_admin: boolean };
}>().props;
const current = tenancy.organizations.find((o) => o.slug === tenancy.current_org);
const switchTo = (slug: string) => {
router.post('/organizations/switch', { slug }, { preserveState: false });
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton size="lg">
<span className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
<Building2Icon className="size-4" />
</span>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{current?.name ?? 'Select workspace'}</span>
<span className="truncate text-xs text-muted-foreground">
{tenancy.current_org ?? 'No workspace active'}
</span>
</div>
<ChevronsUpDownIcon className="ml-auto size-4" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="start">
<DropdownMenuLabel className="flex items-center justify-between text-xs text-muted-foreground">
<span>Workspaces</span>
{tenancy.is_super_admin && (
<span className="inline-flex items-center gap-1 text-amber-500">
<ShieldIcon className="size-3" /> Super Admin
</span>
)}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{tenancy.organizations.map((org) => (
<DropdownMenuItem key={org.slug} onClick={() => switchTo(org.slug)}>
<span className="truncate">{org.name}</span>
{org.slug === tenancy.current_org && <CheckIcon className="ml-auto size-4" />}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}