Runtime Eloquent Scopes via Laravel Service Container | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com) [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles  ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

  [ home ](https://www.msaied.com)    [ articles ](https://www.msaied.com/articles)    Contextual Eloquent Scopes: Binding Query Logic to Domain State at Runtime        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)

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

  #laravel   #eloquent   #architecture   #testing   #service-container  

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

     15 Aug 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

1. [  01   The Problem: Scattered Conditionals in Query Land  ](#the-problem-scattered-conditionals-in-query-land)
2. [  02   Defining a Query Context Contract  ](#defining-a-query-context-contract)
3. [  03   Binding the Context in a Service Provider  ](#binding-the-context-in-a-service-provider)
4. [  04   A Trait That Wires It Into Eloquent  ](#a-trait-that-wires-it-into-eloquent)
5. [  05   Swapping Context in Jobs and Tests  ](#swapping-context-in-jobs-and-tests)
6. [  06   Composing Multiple Contexts  ](#composing-multiple-contexts)
7. [  07   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.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Fcontextual-eloquent-scopes-binding-query-logic-to-domain-state-at-runtime&text=Contextual+Eloquent+Scopes%3A+Binding+Query+Logic+to+Domain+State+at+Runtime) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Fcontextual-eloquent-scopes-binding-query-logic-to-domain-state-at-runtime) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  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. 

      Q02  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. 

      Q03  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. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://www.msaied.com/articles) 

 [ ![Octane Worker Lifecycle, State Leakage, and Memory Management in Production](https://cdn.msaied.com/554/8cc265358b47e59601a66d1e247eba9a.png) laravel octane performance 

### Octane Worker Lifecycle, State Leakage, and Memory Management in Production

Laravel Octane keeps workers alive across requests, which means static state, resolved singletons, and stale d...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 16 Aug 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/octane-worker-lifecycle-state-leakage-and-memory-management-in-production-2) [ ![Job Batching with Laravel Horizon: Reliable Async Workflows at Scale](https://cdn.msaied.com/553/b794b736bfd84f3cbcc6218319916544.png) laravel queues horizon 

### Job Batching with Laravel Horizon: Reliable Async Workflows at Scale

Learn how to combine Laravel's job batching API with Horizon's queue supervision to build fault-tolerant async...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 15 Aug 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/job-batching-with-laravel-horizon-reliable-async-workflows-at-scale) [ ![Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms](https://cdn.msaied.com/552/a7825c0c6f53d934f84fce522573eafb.png) laravel eloquent value-objects 

### Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms

Go beyond primitive casts. Learn how to build custom Eloquent cast classes that hydrate value objects, handle...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 15 Aug 2026     1 min read  

  Read    

 ](https://www.msaied.com/articles/contextual-eloquent-casts-custom-cast-classes-value-objects-and-inbound-only-transforms) 

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

Explore

- [Home](https://www.msaied.com)
- [Projects](https://www.msaied.com/projects)
- [Articles](https://www.msaied.com/articles)
- [Certificates](https://www.msaied.com/certificates)
- [Contact](https://www.msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
