Skip to content

Scoping

Scoped settings allow you to store and retrieve values that are linked to a specific Eloquent model, such as a User, Team, Tenant, or any other entity.

This feature is useful when you want personalized settings per user, customer, team, etc.


๐Ÿ‘ค Scoping to a model

You can associate a setting with a specific model using for($model):

$user = User::find(1);
setting()->for($user)->set('dashboard.layout', 'compact');

$layout = setting()->for($user)->get('dashboard.layout');
// 'compact'

This setting will only apply to that user.


๐ŸŽฏ Global vs Scoped

Without for(), settings are considered global:

setting()->set('locale', 'en'); // Global
setting()->for($user)->set('locale', 'it'); // User-specific

You can retrieve the global value explicitly with:

setting()->forGlobal()->get('locale');

๐Ÿ‘ฅ Using custom models

You can scope to any model that extends Illuminate\Database\Eloquent\Model:

$team = Team::find(5);
setting()->for($team)->set('theme', 'dark');

๐Ÿ”„ Overriding global with scoped values

You can have the same key defined at different scopes:

setting()->set('notifications.email', true);             // global
setting()->for($user)->set('notifications.email', false); // scoped

You decide at runtime which to use based on context.


๐Ÿงช Testing scoped values

$user = User::factory()->create();

setting()->for($user)->set('timezone', 'Europe/Rome');

expect(setting()->for($user)->get('timezone'))->toBe('Europe/Rome');

โšก Caching per scope

When using set() on scoped or global settings, you can enable caching by providing a TTL:

setting()->for($user)->set('dashboard.layout', 'compact', 600); // cache 10 minutes

If you omit the TTL, the system will look for defaults in the config:

// uses config('scoped-settings.cache.scoped_ttl') or global_ttl
setting()->for($user)->set('dashboard.layout', 'compact');

Cached values will be returned by get() automatically when available.


๐Ÿ’ก Tip

If you're using the settings in a controller or service and want to keep it scoped to the authenticated user:

setting()->for(auth()->user())->get('some.preference');

๐Ÿ“š Continue with