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'] ?? false),
managementMode: $settings['loyalty_management_mode'] ?? LoyaltyRules::MODE_LOCKED,
modificationScope: $settings['local_modification_scope'] ?? LoyaltyRules::SCOPE_PARTIAL,
editableParts: array_merge($partsDefaults, $settings['editable_parts'] ?? []),
);
}
}
Independent shops get permissive() rules, so the existing behaviour is unchanged for them. That is what let us ship the network rules without touching independents. The static cache exists because Filament re-instantiates services in each render closure, and a table can ask the policy dozens of times per page. It has to be flushed between tests.
The same rules drive propagation. When head office updates a master card, SyncFranchiseLoyaltyCardToTeams never overwrites a part the shop is allowed to edit, and never touches cardholder balances. The lock settings therefore decide both what a shop can change and what the next sync will leave alone.
Settings inheritance stays one line where it's needed:
// AI settings for a team: its own, otherwise its franchise's.
return $this->reviewAiSetting ?? $this->franchise?->reviewAiSetting;
What broke (or would have)
None of these reached a customer: tests or code review caught them.
| Problem | Where it was | What we changed |
|---|---|---|
| Four copies of the network customer perimeter drifting apart | CRM list, KPIs, CSV export, multi-panel resource | One CustomerScope, used by all four |
| Ids from a form trusted as-is | Network campaign and assignment forms | Intersect with the visible perimeter, plus a test that posts an outsider id |
Perimeter checked once, in Livewire mount()
|
Establishment page of the multi panel | Check on every request, plus a test that revokes access mid-session |
Lookup by email + game_id without team_id
|
Public game page, "one play per day" rule |
team_id added to the query, plus a regression test |
| Team gates answering "yes" on the multi panel |
team.* gates |
Separate franchise role checks |
Forged selections. A network campaign or a loyalty card can target establishments "by team" or "by group". Both lists come from the browser, so we treat them as untrusted input:
/**
* Teams targeted by an assignment (game, loyalty card...), chosen by team
* or by group. Always re-intersected with the user's visible perimeter:
* the ids come from the form and can't be trusted.
*/
protected static function assignTeamIds(?string $mode, array $teams, array $groups): array
{
$franchise = static::franchise();
$visibleGroupIds = $franchise->visibleGroupIdsFor(auth()->user());
if ($mode === 'groups') {
if (empty($groups)) {
return [];
}
if ($visibleGroupIds !== null) {
$groups = array_intersect(array_map('intval', $groups), $visibleGroupIds);
}
return FranchiseTeamGroup::query()
->whereIn('id', $groups)
->where('franchise_id', $franchise->id)
->with('teams:id')
->get()
->flatMap(fn (FranchiseTeamGroup $group) => $group->teams->pluck('id'))
->unique()
->values()
->all();
}
$teamIds = array_values(array_unique(array_map('intval', $teams)));
// ...intersected with $franchise->visibleTeams(), group restriction or not
return $teamIds;
}
Look at ->where('franchise_id', $franchise->id) on the group query. Without it, a group id from another network would resolve to that network's shops.
Livewire properties are checked once unless you check them again. An establishment page in the multi panel received teamId as a #[Locked] property, so the browser couldn't change it. The perimeter check ran in mount() only. Every later request (a click, a refresh) trusted the locked id, even after head office had revoked the module. #[Locked] guarantees the value hasn't been tampered with. It doesn't guarantee the user is still allowed to see it. The fix resolves through the same check on every request:
#[Locked]
public int $teamId;
private ?Team $loaded = null;
/** A visible establishment of an active network, 404 otherwise. */
public static function resolve(int $teamId): Team
{
$franchise = filament()->getTenant();
abort_unless(
PresenceAccess::isActive($franchise)
&& in_array($teamId, (new NetworkScope($franchise))->teamIds(), true),
404,
);
return Team::with('presenceState')->findOrFail($teamId);
}
/** Perimeter re-checked on each request, then memoised for the rest of it. */
private function team(): Team
{
return $this->loaded ??= self::resolve($this->teamId);
}
$loaded is a private property, so Livewire doesn't serialise it, and it is empty again at the start of every request.
A missing team_id doesn't fail, it returns someone else's row. The public game page looked up a previous player by email and game id to enforce "one play per day". With no team_id in the query, a player recorded under another establishment could block a legitimate one:
$player = Player::query()
->where('team_id', $this->game->team_id)
->where('game_id', $this->game->id)
->where('email', $this->userForm['email'])
->first();
This is what a global scope would have prevented here. We still prefer the explicit where, plus a test that creates the same player in another team and asserts they can still play.
Gates written for shops say yes on the network panel. Our establishment permissions are gates named team.<permission>. On the multi panel there is no team tenant, and the gate returns true for a franchise tenant because "the franchise has its own rules". It does, but only because we added them: HiddenForViewOnly on resources and a writableBy scope for write targets.
Wiring it into Laravel
The gates live in AppServiceProvider. Support and super-admin accounts short-circuit everything, and establishment permissions resolve against the team passed in or the current tenant:
Gate::before(function (User $user, string $ability) {
return $user->isSuperAdmin() || $user->isGhost() ? true : null;
});
// Establishment roles: gate "team.<permission>" on the given team or the
// current tenant. On the multi panel (franchise tenant) no team role applies:
// the franchise enforces its own roles.
foreach (TeamPermission::cases() as $permission) {
Gate::define('team.'.$permission->value, function (User $user, ?Team $team = null) use ($permission) {
$tenant = $team ?? filament()->getTenant();
return $tenant instanceof Team
? $user->canInTeam($tenant, $permission)
: $tenant instanceof Franchise;
});
}
The franchise roles come from the franchise_user pivot. A view-only member doesn't see write resources, and isn't offered as a duplication target:
trait HiddenForViewOnly
{
public static function canAccess(): bool
{
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
return $user->currentFranchiseRole() !== FranchiseRole::ViewOnly;
}
}
// On Franchise: networks where the user can write (duplication targets).
public function scopeWritableBy(Builder $query, ?User $user): Builder
{
if ($user?->isGhost()) {
return $query;
}
return $query
->when(! $user?->has_multi_panel, fn ($q) => $q->whereRaw('0 = 1'))
->whereHas('users', fn ($u) => $u
->whereKey($user?->id)
->where('franchise_user.role', '!=', FranchiseRole::ViewOnly->value));
}
Resources and Livewire forms in the multi panel share a ResolvesFranchiseScope trait (franchise(), teamIds(), billingOwner(), assignTeamIds()), so visibleTeams() and getTenant() calls don't end up scattered across the panel. Its methods are static, so a Filament resource (static context) and a Livewire instance can both call them.
Testing
The perimeters have feature tests that build a small network and check who sees what. The group rules are tested directly on the model:
public function test_user_with_two_groups_sees_union_deduplicated(): void
{
$user = User::factory()->create();
$user->franchiseTeamGroups()->attach([$this->groupA->id, $this->groupB->id]);
// teamA1 in both groups: it must appear once
$this->groupB->teams()->attach($this->teamA1->id);
$ids = $this->franchise->visibleTeams($user)->pluck('teams.id')->all();
$this->assertEqualsCanonicalizing(
[$this->teamA1->id, $this->teamA2->id, $this->teamB1->id],
$ids,
);
$this->assertCount(3, $ids);
}
public function test_visible_group_ids_scoped_to_franchise(): void
{
$user = User::factory()->create();
$otherFranchise = Franchise::create(['name' => 'Other', 'email' => 'other@example.test']);
$otherGroup = FranchiseTeamGroup::create(['franchise_id' => $otherFranchise->id, 'name' => 'Other group']);
$user->franchiseTeamGroups()->attach($otherGroup->id);
// Restricted in the other network, unrestricted in this one
$this->assertNull($this->franchise->visibleGroupIdsFor($user));
$this->assertSame([$otherGroup->id], $otherFranchise->visibleGroupIdsFor($user));
}
Livewire tests set the panel and the tenant explicitly, then try to break out of the perimeter:
protected function setUp(): void
{
parent::setUp();
Http::fake(); // observers call external services
$this->franchise = Franchise::create(['name' => 'F', 'email' => 'f@example.test']);
$this->teamA = Team::factory()->create(['franchise_id' => $this->franchise->id]);
// ...
$this->actingAs(User::factory()->create());
Filament::setCurrentPanel(Filament::getPanel('multi'));
Filament::setTenant($this->franchise);
}
public function test_a_forged_selection_cannot_leave_the_visible_scope(): void
{
$outsider = Team::factory()->create(); // not in the network
$this->customer($outsider->id, '0600000009');
$this->customer($this->teamA->id, '0600000001');
Livewire::test(SmsCampaignForm::class)
->set('segments', ['all'])
->set('targetTeams', [$this->teamA->id, $outsider->id])
->call('recomputeContacts')
->assertSet('contactOptin', 1)
->set('name', 'Forge')
->set('sender', 'NETWORK')
->set('message', 'Hello')
->call('persist', 'draft');
$campaign = MarketingCampaign::where('franchise_id', $this->franchise->id)->firstOrFail();
$this->assertSame([$this->teamA->id], $campaign->target_team_ids);
}
The deduplicated customer list has its own tests: same email in two shops gives one row, same phone without email gives one row, and two customers with no contact details are never merged. Shared state like LoyaltyRulesResolver::flush() is reset between tests.
Security
The rules we follow on every network feature:
| Rule | Why |
|---|---|
Multi resources set $isScopedToTenant = false and define getEloquentQuery() themselves |
Filament can't scope Customer to a Franchise. The query has to say it |
Perimeters come from visibleTeams() or a scope object, never rebuilt inline |
Inline copies drift |
| Ids from forms and Livewire properties are intersected with the perimeter, on every request |
#[Locked] protects the value, not the authorisation |
Group lookups always add where('franchise_id', ...)
|
A group id from another network would resolve |
| Caches keyed by perimeter (franchise + hash of visible teams) | Two regional managers don't share a cache |
| Inheritance defaults are restrictive | A network that hasn't configured anything locks rather than leaks |
Wrapping up
- A nullable parent foreign key and a second Filament panel got us a franchise level without touching how independent shops work, or what their queries return.
- Global scopes fit models with one perimeter. Ours depend on the panel, the user's groups and whether a request exists, so an explicit scope object written down in one place was easier to read, test and cache.
- Exclusive ownership (team or franchise) settles billing, deletion and listing questions before they come up.
- Most of the risk sits in inputs: form ids and long-lived Livewire properties. Intersect them with the perimeter, and check it again on every request.
Top comments (0)