Adding a franchise mode to a multi-tenant Laravel SaaS without rewriting it
A regional manager at a national insurance network logs into Up Review and sees the Google reviews, customers and SMS campaigns of the agencies in her region, and nothing from the region next door. Head office sees every agency. It pushes a loyalty card to a whole group of agencies in one action and decides which parts each agency may still change. The agency staff log into the same panel they used before the network arrived, and nothing has changed for them.
This post covers how we added that franchise → establishments hierarchy to a Laravel 12 + Filament 3 SaaS that was built for single shops from day one. We kept one codebase and did not rewrite the existing tenancy. It explains why we chose explicit scope objects over Eloquent global scopes, how the policies decide what a franchise lets its shops do, and which mistakes our tests and reviews caught before they reached production.
TL;DR
- Add the parent level as a nullable foreign key on the tenant you already have (
teams.franchise_id), plus a second Filament panel whose tenant is the franchise. Don't build a second app. - Put each perimeter in one explicit object (
Franchise::visibleTeams(),CustomerScope), not in a global scope. The same model is read under different perimeters depending on the panel, the user and whether a request exists at all. - Make ownership exclusive: a row belongs to a team or a franchise, never both, and enforce it in a
savinghook. - Treat every id that comes from a form or a Livewire property as untrusted. Intersect it with the visible perimeter, and check it again on every request.
- Put inheritance rules ("head office locks the loyalty card design") in a resolver that policies consume, with restrictive defaults.
The context
Up Review is a local-marketing SaaS: Google review management, SMS and email campaigns, digital loyalty cards, and QR-code games. Since 2024, every customer has been a Team (Jetstream), and a team is one establishment. Filament's tenant is the Team, around seventy Eloquent models carry a team_id, and Filament filters resource queries by tenant automatically. There is no global scope anywhere in the codebase.
In 2026, networks started signing: one head office, many agencies, and regional managers in between. Their needs were specific:
- head office sees every establishment, and a regional manager sees only her group;
- head office creates a game, a loyalty card or a campaign once and pushes it to many establishments;
- head office decides what an establishment may still edit on what it received;
- the establishments keep working in the existing panel, with their existing data.
The data model landed in March 2026, and the first network has been using it in production since July 2026. The full project story (timeline, constraints, team) is here.
The initial plan was a second Laravel application for franchises, plugged into the same database. We compared three options:
| Option | What it costs | Why we didn't pick it / why we did |
|---|---|---|
| Second Laravel app, same database | Two deployments, duplicated models, observers and jobs that must stay in sync | Every model change has to ship twice, and the observers (admin-app sync, QR generation) would run in two places |
| Global scopes on every team-scoped model | Retrofitting ~70 models that already run in production, jobs and observers included | The perimeter depends on the panel, the user's groups and the execution context. A global scope has to guess it from ambient state |
| Second Filament panel + explicit scope objects | One new panel, one nullable column, and a scope class per domain | One codebase. Multi-panel resources subclass the existing ones, and every network query says what it reads |
We went with the third.
Step 1: one nullable column, one pivot, one group table
The hierarchy needed very little schema. A team optionally belongs to a franchise:
Schema::table('teams', function (Blueprint $table) { $table->foreignId('franchise_id')->nullable()->constrained()->nullOnDelete(); }); Because it is nullable, every existing team stays an independent shop and no existing query changes. Users join a franchise through a franchise_user pivot that carries a role (admin, compta, user, view_only). Regional perimeters are FranchiseTeamGroup rows, with a pivot to teams and another to users.
The question "which establishments can this user see in this network?" is answered in one place, on the Franchise model:
/** * Group ids the user is restricted to within this franchise. * null = no group restriction, the user sees the whole network. * * @return array<int>|null */ public function visibleGroupIdsFor(?User $user): ?array { if (! $user) { return null; } $ids = $user->franchiseTeamGroups() ->where('franchise_id', $this->id) ->pluck('franchise_team_groups.id') ->all(); return $ids === [] ? null : $ids; } public function visibleTeams(?User $user = null): Builder { $user ??= auth()->user(); $groupIds = $this->visibleGroupIdsFor($user); $query = $this->teams()->getQuery(); if ($groupIds === null) { return $query; } return $query->whereHas( 'franchiseTeamGroups', fn (Builder $q) => $q->whereIn('franchise_team_groups.id', $groupIds) ); } The where('franchise_id', $this->id) matters. A user can be restricted to a group in one network and be unrestricted in another, and our tests cover that case. The other design choice is deliberate and has a cost: no group means the whole network. Head office users need no setup, but a regional manager who was never assigned a group sees everything. That was a product decision, not a technical one.
Step 2: a second Filament panel, not a second app
The franchise side is a second Filament panel, /multi, whose tenant is the Franchise:
class MultiPanelProvider extends PanelProvider { public function panel(Panel $panel): Panel { return $panel ->id('multi') ->path('multi') ->tenant(Franchise::class) // ...navigation groups, theme, middleware ->discoverResources(in: app_path('Filament/Multi/Resources'), for: 'App\\Filament\\Multi\\Resources') ->discoverPages(in: app_path('Filament/Multi/Pages'), for: 'App\\Filament\\Multi\\Pages'); } } The User model tells Filament which tenants exist on which panel. The same methods serve both panels:
public function getTenants(Panel $panel): array|Collection { // Support ("ghost") accounts don't load every tenant into the menu; // they go through a search instead. if ($this->isGhost()) { return collect(); } return $panel->getId() === 'multi' ? $this->franchise()->get() // BelongsToMany via franchise_user : $this->teams()->active()->get(); } public function canAccessTenant(Model $tenant): bool { if ($tenant instanceof Team) { return ($this->isGhost() ? Team::query() : $this->teams())->active()->whereKey($tenant)->exists(); } if ($tenant instanceof Franchise) { return $this->isGhost() || $this->franchise()->whereKey($tenant)->exists(); } return false; } public function canAccessPanel(Panel $panel): bool { if ($panel->getId() === 'admin') { return true; } if ($panel->getId() === 'multi') { return $this->has_multi_panel || $this->isGhost(); } return false; } Most of the reuse comes from resources. Eight of the eleven resources in the multi panel extend the admin resource they mirror, so forms, tables and actions are written once. A network-level coupon looks like this:
use App\Filament\Resources\CouponResource as BaseResource; class CouponResource extends BaseResource { use HiddenForViewOnly; // Filament's automatic tenant scoping is off: we own the query. protected static bool $isScopedToTenant = false; public static function getEloquentQuery(): Builder { return Coupon::query()->where('franchise_id', filament()->getTenant()->id); } // ...pages } In the multi panel, a customer belongs to a team and not to the franchise, so Filament's automatic scoping through a franchise relationship doesn't apply. Each multi resource turns it off with $isScopedToTenant = false and defines getEloquentQuery() itself. That is the line where a cross-tenant leak would start, so we kept these query definitions short and moved anything non-trivial into a dedicated scope class.
Step 3: why we didn't use global scopes
A global scope works when a model has one perimeter, which you can read from ambient state such as the authenticated user or the current tenant. Customer has at least three:
| Context | Perimeter |
|---|---|
Admin panel (tenant = Team) | that shop's customers |
Multi panel (tenant = Franchise) | customers of the teams this user can see, plus contacts imported at network level, with one row per person across shops |
| Queue jobs, console commands, mobile API | no Filament tenant: the caller passes the team explicitly |
A global scope would have had to work out which of these applies from filament()->getTenant() and auth()->user(). In a queued job both are null, so the scope would either filter nothing without telling us or throw. Retrofitting it onto models that observers and jobs already query in production would also have changed behaviour in code we weren't touching. So we kept the existing where('team_id', ...) convention for shops and gave network reads one explicit object per domain. For customers it is CustomerScope:
/** * Customer perimeter for the current tenant. * Exists so there is ONE definition of it: the CRM listing, the KPIs, * the CSV export and the multi-panel resource each had their own copy. */ final class CustomerScope { /** * Identity of a person across shops: email, else phone, else the row itself. * Two rows without contact details are never merged. */ public const IDENTITY_KEY = "COALESCE(NULLIF(email, ''), NULLIF(phone, ''), CONCAT('__id__', id))"; private function __construct( private readonly ?Team $team, private readonly ?Franchise $franchise, private readonly array $teamIds, ) {} public static function current(): self { $tenant = filament()->getTenant(); if ($tenant instanceof Franchise) { return new self( null, $tenant, $tenant->visibleTeams(auth()->user())->pluck('teams.id')->all(), ); } return new self($tenant, null, $tenant?->id ? [$tenant->id] : []); } /** Outside a Filament panel (mobile app): the shop is explicit. */ public static function forTeam(Team $team): self { return new self($team, null, [$team->id]); } public function constrain(Builder $query): Builder { if ($this->franchise !== null) { return $query->where(fn (Builder $q) => $q ->whereIn('team_id', $this->teamIds) ->orWhere('franchise_id', $this->franchise->id)); } if ($this->team !== null) { return $query->where('team_id', $this->team->id); } return $query; // job / console: no perimeter to apply } /** One representative (MIN(id)) per person. Apply AFTER the filters. */ public function dedup(Builder $query): Builder { if ($this->franchise === null) { return $query; } $matched = (clone $query)->select('customers.id'); return $query->whereIn('customers.id', Customer::query() ->whereIn('id', $matched) ->selectRaw('MIN(id) as id') ->groupByRaw(self::IDENTITY_KEY)); } /** * Cache / session key. The visible teams are part of it: two users * restricted to different groups don't see the same network. */ public function key(): string { if ($this->franchise !== null) { $ids = $this->teamIds; sort($ids); return 'franchise.'.$this->franchise->id.'.g'.substr(md5(implode(',', $ids)), 0, 8); } return 'team.'.($this->team?->id ?? 0); } /** The network view is read-only: editing a merged representative makes no sense. */ public function canWrite(): bool { return $this->franchise === null; } // ...custom field definitions, consent helpers } Three details matter. dedup() must run after the filters: a person who matches a filter in only one shop must still be listed. The cache key includes a hash of the visible teams, because two regional managers looking at the same network don't see the same customers. And constrain() returning the query untouched outside a panel is written down explicitly, so a reader can see it. A global scope would do the same without anyone seeing it.
The trade-off is real: every network query has to go through the scope object, and nothing forces a developer to use it. Tests and reviews do that job (see below).
Step 4: a row belongs to a team or a franchise, never both
Some content is created by head office and used by many shops: campaign templates, coupons, publications, media. We added a nullable franchise_id next to team_id on those tables (49 migrations touch franchise_id today) and made ownership exclusive:
/** * Exclusive ownership: an establishment (team) OR a network (franchise), * never both. Same rule as MarketingCampaign and Coupon, factored out * when the Publication module needed it on three more models. */ trait BelongsToTeamOrFranchise { protected static function bootBelongsToTeamOrFranchise(): void { static::saving(function ($model) { if ($model->team_id !== null && $model->franchise_id !== null) { throw new \InvalidArgumentException( class_basename($model).' cannot have both team_id and franchise_id.' ); } }); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function franchise(): BelongsTo { return $this->belongsTo(Franchise::class); } public function owner(): Team|Franchise|null { return $this->franchise ?? $this->team; } public function isNetworkOwned(): bool { return $this->franchise_id !== null; } } With both columns filled, a row would show up in a shop's list and in the network's list. Who pays for a campaign, who can delete it and which list it appears in would all become ambiguous. Throwing on save is crude, but it turns that ambiguity into a stack trace during development. For example, the network SMS campaign is billed to the franchise, never to a shop.
Loyalty cards needed one more shape. Head office owns a master card, and each establishment gets a copy that points back to it with franchise_loyalty_card_id. A "shared" card is a single franchise-owned card served by several shops. The query for "cards usable in this shop" has to say that explicitly:
public function scopeAccessibleBy(Builder $query, Team|int $team): Builder { $teamId = $team instanceof Team ? $team->id : $team; return $query->where(fn (Builder $q) => $q ->where('team_id', $teamId) ->orWhere(fn (Builder $q) => $q ->whereNull('team_id') ->where('multi_mode', self::MULTI_COMMUN) ->whereHas('teams', fn (Builder $t) => $t->whereKey($teamId)))); } Step 5: policies decide what head office lets shops do
Once a shop belongs to a network, the existing policies need to know about the network. Can this shop create its own loyalty card? Can it edit the design of the card head office pushed? We put the rules in a resolver and kept the policy thin:
class LoyaltyCardPolicy { public function __construct(private LoyaltyRulesResolver $rules) {} /** A franchise can forbid its shops from creating their own cards. Outside a franchise, nothing changes. */ public function create(User $user): bool { $team = $user->currentTeam ?? Team::find($user->current_team_id); return $this->rules->forTeam($team)->canCreateLocalCard(); } public function update(User $user, LoyaltyCard $loyaltyCard): bool { return ! $this->rules->forCard($loyaltyCard)->isFullyLocked($loyaltyCard); } // ... } The resolver is where the important default lives:
/** * Restrictive defaults on purpose: without a loyalty_settings row, * a franchise locks everything until it explicitly opens rights. */ class LoyaltyRulesResolver { /** @var array<string, LoyaltyRules> */ private static array $cache = []; public function forTeam(?Team $team): LoyaltyRules { if (! $team || $team->franchise_id === null) { return self::$cache['permissive'] ??= LoyaltyRules::permissive(); } return self::$cache['franchise:'.$team->franchise_id] ??= $this->buildForFranchiseId($team->franchise_id); } public static function flush(): void { self::$cache = []; } private function buildForFranchiseId(int $franchiseId): LoyaltyRules { $settings = LoyaltySetting::where('franchise_id', $franchiseId)->value('settings') ?? []; // ...every editable part defaults to false return new LoyaltyRules( simpleMode: false, localCanCreateCards: (bool) ($settings['local_can_create_cards'Source:https://dev.to/hugobachmann/adding-a-franchise-mode-to-a-multi-tenant-laravel-saas-without-rewriting-it-4e6h