Open source June 2025

Laracontext

Laracontext sets a global context for a Laravel application and lets Eloquent queries scope themselves against it, so a value like the current tenant is declared once instead of threaded through every call.

Installation

composer require edulazaro/laracontext

The package registers itself; there is nothing to publish.

Setting and reading values

The helper covers most uses, and supports dot notation:

context(['tenant_id' => 5]);
$tenantId = context('tenant_id'); // 5

context([
    'group.id'   => 12,
    'group.name' => 'Admins',
]);

$groupId = context('group.id'); // 12

The Context class does the same thing directly:

use EduLazaro\Laracontext\Context;

$context = app(Context::class);

$context->set('user.id', 1);
$context->set(['locale' => 'en']);

$context->get('user.id');
$context->has('user.id');   // true
$context->forget('user.id');
$context->clear();

It also behaves as an array:

$context['timezone'] = 'Europe/Madrid';
echo $context['timezone']; // Europe/Madrid

Scoped queries

Add HasContextScope to a model and declare which context keys it scopes by:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use EduLazaro\Laracontext\Concerns\HasContextScope;

class Dog extends Model
{
    use HasContextScope;

    public static array $context = ['tenant_id'];
}

With the context set:

context(['tenant_id' => 1]);

Dog::context()->get();
// equivalent to Dog::where('tenant_id', 1)->get()

Mapping keys

When the column and the context key differ:

public static array $context = [
    'tenant_id' => 'custom.tenant',
];
context(['custom.tenant' => 1]);

Dog::context(); // where tenant_id = 1

Passing a model

A model can be the context value directly. The trait calls getKey() on it:

context(['tenant' => $tenantModel]);

Snapshot and restore

$snapshot = context()->snapshot();

context()->clear();

// ...do stuff...

context()->restore($snapshot);

Testing

Clear the context before each test so values do not leak between them:

context()->clear();

For total isolation, bind a fresh instance:

$this->app->singleton(Context::class, fn () => new Context());

built and maintained by Edu Lazaro · MIT license