---
title: "Thread context — Messages for Laravel | Roundly"
description: "Tie a conversation to a company, project or order — one DM per pair per context, context-aware listings, and a fail-closed hook for multi-tenant isolation."
url: https://roundly-consulting.com/open-source/docs/messages-for-laravel/thread-context
language: en
---

[All packages](https://roundly-consulting.com/open-source.md)

[Messages for Laravel](https://roundly-consulting.com/open-source/docs/messages-for-laravel.md)

# Thread context

Since 2.2.0. A thread may belong to a context — the company, project or order a conversation is about. Any saved model works (an unsaved one throws ThreadContextException::unsaved()), as long as its key type matches key\_type. It is optional: a thread without a context behaves exactly as before.

```php
// Start in a context
$thread = Messages::start('Quote #812')->for($company)->withParticipants([$agent, $customer])->create();
$thread = $agent->startConversationWith($customer, 'Quote #812', context: $company);

// One DM per pair per context
$dm = Messages::direct($agent, $customer, $company);
$dm = $agent->conversationWith($customer, $company);

// Listing and lookup — each narrows to the context when given one
Messages::inboxFor($agent, context: $company);
Messages::threads($agent, context: $company);
Messages::unreadCount($agent, context: $company);
$agent->threads($company); $agent->unreadThreads($company); $agent->unreadCount(context: $company);

// Query scopes
Thread::query()->forContext($company)->get();
Thread::query()->withoutContext()->get();
$thread->context;                // the company (MorphTo)
$thread->isInContext($company);  // bool
```

- start()->for($context) starts a thread in a context; the trait’s startConversationWith() takes it as context:.
- direct($a, $b, $context) and conversationWith($other, $context) keep one DM per pair per context, plus one without: a DM in context A is never returned for context B or for none. The pair key carries the context (Thread::directKeyFor($a, $b, $context)), so the lookup stays race-safe.
- inboxFor(), threads() and unreadCount() — and the trait’s threads(), conversations(), unreadThreads() and unreadCount() — narrow to one context when given one.
- Thread::forContext($model) and Thread::withoutContext() are plain query scopes; Thread::between() matches any context. $thread->context is a MorphTo, $thread->isInContext(?Model) a quick check (null = has none).

## The fail-closed hook

In a multi-company app, make the context a boundary: register a resolver once, and while it returns a context every thread query is limited to exactly that context:

```php
// AppServiceProvider::boot() — a closure …
Messages::resolveContextUsing(fn (): ?Company => app(CurrentCompany::class)->get());

// … or a class, resolved from the container (config:cache friendly)
// config/messages.php: 'context' => ['resolver' => App\Messaging\CurrentCompanyContext::class],
final class CurrentCompanyContext implements \RoundlyConsulting\Messages\Interfaces\ResolvesThreadContext
{
    public function currentContext(): ?Model { return app(CurrentCompany::class)->get(); }
}
```

- Reads — Thread::query(), find(), route-model binding, inboxFor(), threads(), unreadCount(), direct()’s lookup, a message’s or participant’s thread relation and the thread broadcast-channel authorisation all see only that context’s threads (the ThreadContextScope global scope). A thread of another context, or one without a context, is simply not found.
- Held instances — the API refuses a thread of another context it is handed with ThreadContextException::outsideCurrentContext(): to(), send(), thread() and every handle method behind it, markRead(), message(), unreadCount($p, $thread), prune(thread:) and the model helpers that go through them.
- Writes — start()->create() and direct() without a context use the current one; asking for another one throws ThreadContextException::mismatch().
- A bad resolver never yields an unconstrained query: a closure returning neither a model nor null throws invalidResolution(), an unsaved model unsaved(), a misconfigured class InvalidConfigurationException.

A resolver returning null means no constraint — console commands, queued jobs, an admin area. Step outside it explicitly when you need to:

```php
Messages::currentContext();                                    // ?Model — the context queries are limited to now
Messages::withoutContextScope(fn () => Thread::query()->count());  // the hook off for one block (admin, jobs)
Thread::withoutGlobalScope(ThreadContextScope::class)->get();  // or for one query
Messages::resolveContextUsing(null);                            // remove the closure
```

The resolver runs on every thread query, so keep it cheap and never query threads inside it (that recurses). The scope constrains threads: Message::find() and Participant::find() on their own are not constrained — reach them through a thread, or through Messages::message(), which refuses. prune() without a thread is maintenance and prunes every context. The hook lives in a container singleton, so Messages::fake() keeps it, and php artisan about shows Context scope: ON or OFF (INVALID for a misconfigured class).

## In JSON

ThreadResource renders context only when the relation is loaded — $thread->load('context') or ->with('context'); the package’s own listings do not load it. It goes through resources.context, by default ThreadContextResource, which never exposes a class name:

```json
"context": { "id": 7, "type": "Company" }   // ThreadResource — only when the context relation is loaded; null for none
```

ThreadContextResource::configured(?Model $context) builds the configured resource. In tests, assertThreadCreated(context: $company) checks the context a thread was created in — asked for, or taken from the hook.

## Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

[More ways to support, including crypto](https://roundly-consulting.com/support-us.md)

By donating, you agree to our [donation terms](https://roundly-consulting.com/donation-terms.md).

[Support our open source work (opens in a new tab)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Join us on Patreon (opens in a new tab)](https://www.patreon.com/cw/roundly)

## Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.

[Get a quote in 48 hours](https://roundly-consulting.com/contact.md) [Browse all packages](https://roundly-consulting.com/open-source/docs/messages-for-laravel.md)
