ENGINEERING JOURNAL

Laravel Multi-Tenant Query Scoping: Every Query, One Organization

Scope every query by organization in a multi-tenant Laravel app with a global scope and trait, so tenant data stays private and cross-tenant leaks cannot happen.

THE ARTICLE 01 — 02

A multi-tenant Laravel app has one rule that matters more than any other: every query touches exactly one organization. Miss the scope on a single query and one customer sees another customer's data. That is not a bug you can patch later with an apology. This post shows how to do Laravel multi-tenant query scoping with a global scope, so the boundary holds even on the day you forget to add it by hand.

Why scoping by hand always fails eventually

The obvious approach is to add where('organization_id', $orgId) to every query. It works until it does not. A new developer joins and writes a report query without it. You add a relationship and forget the constraint rides on the parent, not the child. A search endpoint takes a shipment ID from the URL and loads it directly with findOrFail. Each of these is a small, reasonable line of code. Together they are a leak waiting to happen. The fix is to move the rule out of every controller and into the model layer, where it applies by default.

A global scope that applies the tenant automatically

Laravel global scopes run on every query for a model. That makes them the right place for a tenant filter. First, a small holder for the current organization:

<?php

namespace App\Support;

class CurrentOrganization
{
    protected static ?int $id = null;

    public static function set(?int $id): void
    {
        static::$id = $id;
    }

    public static function id(): ?int
    {
        return static::$id;
    }
}

Then the scope itself:

<?php

namespace App\Scopes;

use App\Support\CurrentOrganization;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class OrganizationScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $organizationId = CurrentOrganization::id();

        if ($organizationId !== null) {
            $builder->where(
                $model->qualifyColumn('organization_id'),
                $organizationId
            );
        }
    }
}

Using qualifyColumn matters. Once you join another table that also has an organization_id column, an unqualified where turns into an ambiguous column error. Qualify it from the start and you never chase that bug.

One trait for every tenant-owned model

Apply the scope through a trait so every tenant-owned model gets it the same way:

<?php

namespace App\Models\Concerns;

use App\Scopes\OrganizationScope;
use App\Support\CurrentOrganization;

trait BelongsToOrganization
{
    protected static function bootBelongsToOrganization(): void
    {
        static::addGlobalScope(new OrganizationScope);

        static::creating(function ($model) {
            if ($model->organization_id === null) {
                $model->organization_id = CurrentOrganization::id();
            }
        });
    }

    public function organization()
    {
        return $this->belongsTo(\App\Models\Organization::class);
    }
}

The creating hook fills in organization_id on new records, so inserts are scoped the same way reads are. A model uses it with one line:

class Shipment extends Model
{
    use BelongsToOrganization;
}

This is the pattern I use in ClaimTrail, a multi-tenant app where carriers, shipments, and claims all belong to an organization. The trait is what keeps the rule consistent across dozens of models instead of living in each controller.

Set the organization once per request

The scope is only as good as the value it reads. Set the current organization in middleware, right after authentication:

public function handle(Request $request, Closure $next): Response
{
    $user = $request->user();

    if ($user !== null) {
        CurrentOrganization::set($user->organization_id);
    }

    return $next($request);
}

Register it in the web and api middleware groups so every authenticated request sets it. Queue jobs and console commands do not run through HTTP middleware, so any job that touches tenant data must set the organization itself at the start of handle(), using the organization stored on the job payload. A job that reads tenant data without setting it first runs with no scope at all, which is the one case this design leaves open. Treat that as a code review rule: a job touching tenant models sets the organization before its first query.

Prove the isolation with a test

A scope you never test is a scope you trust on faith. The test that matters most is the negative one: data from organization B must be invisible while organization A is active.

public function test_users_cannot_see_another_organizations_shipment(): void
{
    $orgA = Organization::factory()->create();
    $orgB = Organization::factory()->create();

    Shipment::factory()->for($orgA, 'organization')->create();
    Shipment::factory()->for($orgB, 'organization')->create();

    CurrentOrganization::set($orgA->id);

    $this->assertCount(1, Shipment::all());
}

Write one of these for every tenant-owned model, and add a second test that loads a record by ID from the other organization and expects a 404. That second test catches the findOrFail case from the first section, where a user guesses an ID in the URL. If your cross-tenant isolation checks pass in CI on every push, the boundary survives refactors and new developers.

The escape hatch, and why it needs a review

Sometimes you genuinely need to cross the boundary: an admin report, a data migration, a console command that reassigns records. Laravel lets you drop a scope for one query:

Shipment::withoutGlobalScope(OrganizationScope::class)->get();

Use it sparingly and make every use visible. In code review, withoutGlobalScope should get the same attention as a raw query or a permission change. If a feature needs it often, that is a sign the feature belongs in an admin context with its own authorization, not scattered through normal controllers.

The takeaway

Laravel multi-tenant query scoping works best when the rule lives in one place and applies by default: a global scope that reads the current organization, a trait that attaches it to every tenant-owned model, middleware that sets the organization per request, and tests that prove the other tenant's rows stay invisible. Manual where clauses are fine as a supplement, but they are not the boundary. The scope is. For the bigger picture of where this kind of logic belongs in your app, see Structuring a Laravel API: Controllers, Services, and Where Logic Lives.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗