Runtime Eloquent Scopes via Laravel Service Container | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Contextual Eloquent Scopes: Binding Query Logic to Domain State at Runtime

 Contextual Eloquent Scopes: Binding Query Logic to Domain State at Runtime
===========================================================================

 Learn how to attach runtime-aware query scopes to Eloquent models using the service container, avoiding scattered conditionals and keeping domain rules close to the data layer.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 15 Aug 2026 · Updated 15 Aug 2026 · 3 min read

ShareCopy linkCopied

 ![Contextual Eloquent Scopes: Binding Query Logic to Domain State at Runtime](https://cdn.msaied.com/551/dc00bc1e6fb2999c99a0b5b8fb42a8c3.png) 

  On this page +1. [The Problem: Scattered Conditionals in Query Land](#the-problem-scattered-conditionals-in-query-land)
2. [Defining a Query Context Contract](#defining-a-query-context-contract)
3. [Binding the Context in a Service Provider](#binding-the-context-in-a-service-provider)
4. [A Trait That Wires It Into Eloquent](#a-trait-that-wires-it-into-eloquent)
5. [Swapping Context in Jobs and Tests](#swapping-context-in-jobs-and-tests)
6. [Composing Multiple Contexts](#composing-multiple-contexts)
7. [Key Takeaways](#key-takeaways)

 The Problem: Scattered Conditionals in Query Land
-------------------------------------------------

Every sufficiently complex Laravel application eventually grows a `scopeVisible`, `scopeForTenant`, or `scopeAccessible` that reads from `auth()->user()` or `app('context')` inside the model. It works — until you need to test it in isolation, swap the context in a job, or reuse the same model under different access rules in the same request.

The real issue is that the *who is asking* logic bleeds into the *what to fetch* logic. This article shows a clean way to separate them using contextual binding and a tiny resolver contract.

Defining a Query Context Contract
---------------------------------

Start with a small interface that any "context" must satisfy:

```php
namespace App\Contracts;

use Illuminate\Database\Eloquent\Builder;

interface AppliesQueryContext
{
    public function apply(Builder $query): Builder;
}

```

Now create a concrete implementation for the authenticated user context:

```php
namespace App\Query\Contexts;

use App\Contracts\AppliesQueryContext;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

final class UserQueryContext implements AppliesQueryContext
{
    public function __construct(private readonly User $user) {}

    public function apply(Builder $query): Builder
    {
        return $query->where('team_id', $this->user->team_id)
                     ->where('is_archived', false);
    }
}

```

Binding the Context in a Service Provider
-----------------------------------------

Register the binding in `AppServiceProvider` (or a dedicated `QueryContextServiceProvider`):

```php
$this->app->scoped(AppliesQueryContext::class, function () {
    $user = auth()->user();

    if (! $user) {
        return new NullQueryContext(); // no-op implementation
    }

    return new UserQueryContext($user);
});

```

`scoped()` ensures the same instance is reused for the entire request or job lifecycle — critical for consistency and performance.

A Trait That Wires It Into Eloquent
-----------------------------------

```php
namespace App\Concerns;

use App\Contracts\AppliesQueryContext;
use Illuminate\Database\Eloquent\Builder;

trait HasQueryContext
{
    public function scopeWithContext(Builder $query): Builder
    {
        return app(AppliesQueryContext::class)->apply($query);
    }
}

```

Add the trait to any model:

```php
class Post extends Model
{
    use HasQueryContext;
}

```

Now callers write:

```php
Post::withContext()->latest()->paginate();

```

No `auth()` calls inside the model. No hidden globals.

Swapping Context in Jobs and Tests
----------------------------------

In a queued job that runs on behalf of a specific team, rebind before dispatching work:

```php
app()->instance(
    AppliesQueryContext::class,
    new TeamQueryContext($team)
);

```

In Pest, override the binding per test:

```php
it('only returns posts for the correct team', function () {
    $team = Team::factory()->create();
    $other = Team::factory()->create();

    Post::factory()->for($team)->count(3)->create();
    Post::factory()->for($other)->count(2)->create();

    app()->instance(
        AppliesQueryContext::class,
        new UserQueryContext(User::factory()->for($team)->make())
    );

    expect(Post::withContext()->count())->toBe(3);
});

```

No `actingAs`, no session bootstrapping — just a clean container swap.

Composing Multiple Contexts
---------------------------

For multi-tenant SaaS where you need both tenant isolation *and* soft-delete filtering, compose contexts:

```php
final class CompositeQueryContext implements AppliesQueryContext
{
    /** @param AppliesQueryContext[] $contexts */
    public function __construct(private array $contexts) {}

    public function apply(Builder $query): Builder
    {
        foreach ($this->contexts as $context) {
            $query = $context->apply($query);
        }
        return $query;
    }
}

```

Bind it once in the provider and every model using `HasQueryContext` gets all rules applied automatically.

Key Takeaways
-------------

- Use `scoped()` bindings so the context is resolved once per request/job, not on every query.
- A `NullQueryContext` no-op keeps unauthenticated paths safe without null checks.
- The `withContext()` scope is opt-in — models that don't need it stay untouched.
- Composing contexts scales cleanly to multi-tenant + role-based + soft-delete rules.
- Swapping the binding in tests eliminates the need for HTTP-layer setup when testing query logic.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [eloquent](https://www.msaied.com/public/articles?search=eloquent)
- [architecture](https://www.msaied.com/public/articles?search=architecture)
- [testing](https://www.msaied.com/public/articles?search=testing)
- [service-container](https://www.msaied.com/public/articles?search=service-container)

 Frequently asked questions 
---------------------------

  Why use `scoped()` instead of `singleton()` for the query context binding?`scoped()` resets between requests in long-running runtimes like Octane, preventing one user's context from leaking into the next request. `singleton()` would persist for the entire worker lifetime.

   Does adding `withContext()` to every query hurt performance?No. The context object is resolved once per request from the container cache. The `apply()` call just adds WHERE clauses to the existing Builder instance — there is no extra query or reflection overhead.

   Can this pattern work with Filament table queries?Yes. Override `getEloquentQuery()` in your Filament Resource and call `parent::getEloquentQuery()-&gt;withContext()`. The context binding is already in the container at that point in the request lifecycle.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleTesting Filament Resources, Actions, and Form Assertions with Pest](https://www.msaied.com/public/articles/testing-filament-resources-actions-and-form-assertions-with-pest-3) [Next articleContextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms](https://www.msaied.com/public/articles/contextual-eloquent-casts-custom-cast-classes-value-objects-and-inbound-only-transforms)  

   On this page
-------------

1. [The Problem: Scattered Conditionals in Query Land](#the-problem-scattered-conditionals-in-query-land)
2. [Defining a Query Context Contract](#defining-a-query-context-contract)
3. [Binding the Context in a Service Provider](#binding-the-context-in-a-service-provider)
4. [A Trait That Wires It Into Eloquent](#a-trait-that-wires-it-into-eloquent)
5. [Swapping Context in Jobs and Tests](#swapping-context-in-jobs-and-tests)
6. [Composing Multiple Contexts](#composing-multiple-contexts)
7. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
