ahs12 / laravel-setanjo
Laravel settings package for managing application configurations, user preferences, feature flags, and A/B testing with multi-tenant support
Fund package maintenance!
Requires
- php: ^8.4
- illuminate/contracts: ^12.0||^13.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^11.0.0||^10.0.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-arch: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- spatie/laravel-ray: ^1.35
- symfony/yaml: ^7.0||^8.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-11-16 16:42:13 UTC
README
A powerful Laravel package for managing application settings and configurations. Store global application settings or model-specific configurations (user preferences, company settings, etc.) with automatic type casting, caching, and a clean API. Perfect for feature flags, A/B testing, user preferences, and dynamic configuration management.
Note: This package does not provide multi-tenancy features for your application. However, if your Laravel project already has multi-tenancy implemented, this package can store tenant-specific settings alongside your existing tenant architecture.
Features
- π’ Multi-Tenant Ready: Works with existing multi-tenant applications
- ποΈ Model-Specific Settings: Store settings for any Eloquent model (User, Company, etc.)
- ποΈ Global Settings: Application-wide settings without model scope
- β‘ Caching: Optional caching with configurable cache store
- π Validation: Validate models and prevent unauthorized access
- π¦ Clean API: Simple, intuitive API for setting and retrieving values
- π§ͺ Fully Tested: Comprehensive test suite included
- β Type Safety: Automatic type detection and conversion
- π Definitions in Code: Declare settings on an enum (default, type, label, group, rules, meta)
- π© Feature Flags: Global flags with per-user / per-tenant / any-scope overrides, schedules, percentage rollouts, required flags and archiving
- π Scope Chain: Resolve effective values through user β branch β tenant β global β default
- π·οΈ Metadata: Free-form JSON meta per setting (unit, min, max, options, help, sensitive, ...)
- ποΈ Groups & Ordering: Group settings and order groups and settings (drag-and-drop ready)
- π Sync, Export, Import: Keep the database in line with code; move settings between environments
- π£ Events & History: Hook audit logging into events, or let the package record history
- π₯οΈ Dashboard: A built-in UI for settings, groups, flags, overrides, drift, history and import/export
- π HTTP API: Everything the dashboard does, as a JSON API for your own admin UI or services
Requirements
- PHP 8.4 or higher
- Laravel 12.0 or 13.0
Version Compatibility
| Package version | Laravel | PHP | Testbench | Status |
|---|---|---|---|---|
3.x |
12, 13 | ^8.4 |
10, 11 | Active |
2.x |
12, 13 | ^8.4 |
10, 11 | Maintenance (bug fixes) |
1.x |
10, 11, 12 | ^8.2 |
8, 9, 10 | Legacy |
If you are on Laravel 10/11 or PHP 8.2/8.3, install the 1.x line:
composer require "ahs12/laravel-setanjo:^1.0"
To stay on 2.x for now:
composer require "ahs12/laravel-setanjo:^2.0"
Installation
- Install the package:
composer require ahs12/laravel-setanjo
- Publish config and migrations, then migrate:
php artisan setanjo:install
Or step by step:
php artisan vendor:publish --tag="setanjo-migrations"
php artisan migrate
Upgrading from 2.x? See UPGRADE.md.
- Configure tenancy mode (optional):
By default, the package runs in strict mode (single tenant model type).
For basic setup with User model, no configuration needed. For other models or multiple tenant types:
php artisan vendor:publish --tag="setanjo-config"
Quick Setup
Option 1: Strict Mode (Default - Single Tenant Type)
Perfect for simple user preferences or single-model tenancy:
// Uses App\Models\User by default // No configuration needed
Option 2: Custom Strict Mode
For using a different model as the single tenant type:
// config/setanjo.php 'tenancy_mode' => 'strict', 'strict_tenant_model' => App\Models\Company::class,
Option 3: Polymorphic Mode
For multiple tenant model types (SaaS apps, complex multi-tenancy):
// config/setanjo.php 'tenancy_mode' => 'polymorphic', 'allowed_tenant_models' => [ App\Models\User::class, App\Models\Company::class, App\Models\Organization::class, ],
Basic Usage
Global Settings
use Ahs12\Setanjo\Facades\Settings; // Set application-wide settings Settings::set('app_name', 'My Application'); Settings::set('maintenance_mode', false); // Get with default fallback $appName = Settings::get('app_name', 'Default Name');
Tenant Settings (Strict Mode)
// User-specific settings (default tenant model) $user = User::find(1); Settings::for($user)->set('theme', 'dark'); Settings::for($user)->set('language', 'en'); // Or by tenant ID Settings::forTenantId(1)->set('notifications', true); echo Settings::for($user)->get('theme'); // 'dark'
Tenant Settings (Polymorphic Mode)
// Different model types as tenants $user = User::find(1); $company = Company::find(1); Settings::for($user)->set('theme', 'dark'); Settings::for($company)->set('timezone', 'UTC'); // Or by tenant ID with model class Settings::forTenantId(1, Company::class)->set('currency', 'USD');
Type Casting
Settings::set('is_active', true); // Boolean Settings::set('max_users', 100); // Integer Settings::set('rate', 4.99); // Float Settings::set('features', ['api', 'sms']); // Array Settings::set('config', '{"theme": "dark", "lang": "en"}'); // JSON string Settings::set('metadata',['version' => '1.0', 'author' => 'John']); // Object // Values are returned with correct types $isActive = Settings::get('is_active'); // Returns boolean true $maxUsers = Settings::get('max_users'); // Returns integer 100 $rate = Settings::get('rate'); // Returns float 4.99 $features = Settings::get('features'); // Returns array ['api', 'sms'] $config = Settings::get('config'); // Returns the JSON string as stored $metadata = Settings::get('metadata'); // Returns array ['version' => '1.0', 'author' => 'John']
Definitions
Declare settings and feature flags in code. Values stay in the database; the definition supplies the default, type, label, group, validation rules and meta.
use Ahs12\Setanjo\Contracts\SettingDefinition; use Ahs12\Setanjo\Traits\DefinesSetting; enum SettingKey: string implements SettingDefinition { use DefinesSetting; // sensible defaults, override what you need case COMPANY_NAME = 'company_name'; case AUDIT_RETENTION = 'audit_retention'; case TAX_FEATURES = 'tax_features'; public function default(): mixed { return match ($this) { self::COMPANY_NAME => 'Acme', self::AUDIT_RETENTION => 180, self::TAX_FEATURES => false, }; } public function group(): ?string { return match ($this) { self::COMPANY_NAME => 'Company', default => 'System', }; } public function rules(): array|string { return $this === self::COMPANY_NAME ? 'string|max:100' : []; } public function meta(): array { return match ($this) { self::AUDIT_RETENTION => ['unit' => 'days', 'min' => 1, 'max' => 3650], default => [], }; } public function isFeature(): bool { return $this === self::TAX_FEATURES; } }
Register it in config/setanjo.php (inline arrays work too):
'definitions' => [ App\Enums\SettingKey::class, 'site_name' => ['default' => 'My App', 'group' => 'general'], 'new_checkout' => ['feature' => true], ],
With a definition:
Settings::get('audit_retention')returns the default (180) until a value is stored.- The type is fixed:
Settings::set('audit_retention', '90')stores the integer90. - Values are validated against
rules()and metamin/max/options, otherwiseInvalidSettingValueExceptionis thrown. - Keys accept enum cases:
Settings::get(SettingKey::COMPANY_NAME). scopes()limits which models may override a key, e.g.[Company::class].
Then create the rows and groups:
php artisan setanjo:sync # add missing keys, create groups php artisan setanjo:sync --dry-run # preview php artisan setanjo:sync --prune # also delete keys that are no longer defined
Effective Values and the Scope Chain
get() reads only the current scope. effective() walks a chain of scopes, most specific
first, then global, then the definition default.
// AppServiceProvider::boot() Settings::resolveScopesUsing(fn ($user) => [$user, $user?->branch, $user?->tenant]); Settings::for($user)->effective('audit_retention'); // user β branch β tenant β global β default Settings::effective('audit_retention'); // uses the authenticated user $resolved = Settings::for($user)->explain('audit_retention'); $resolved->value; // 90 $resolved->source; // ValueSource::SCOPE | GLOBAL | DEFAULT $resolved->scope; // the model that supplied the value
The whole chain loads in one query and is cached per scope.
Feature Flags
Flags are stored in their own tables, apart from settings: setanjo_features holds one row per
flag (global state, name, group, order, meta) and setanjo_feature_overrides holds one row per
scope override. Settings::set() refuses keys defined as features.
Settings::feature('tax_features')->enabled(); // for the authenticated user Settings::feature('tax_features')->for($user)->enabled(); Settings::feature('tax_features')->enable(); // global Settings::feature('tax_features')->for($tenant)->disable(); // tenant override Settings::feature('tax_features')->for($user)->inherit(); // remove the user override Settings::feature('tax_features')->for($user)->override(); // true, false or null (inherits) Settings::features()->for($user)->all(); // ['tax_features' => true, ...]
On a model, add HasFeatures: $user->hasFeature('tax_features'), $user->enableFeature(...),
$user->inheritFeature(...), $user->featureStates().
Routes, Blade and Gate:
Route::middleware('setanjo.feature:tax_features')->group(...); // 403 when disabled Route::middleware('setanjo.feature:tax_features,new_checkout')->get(...); // all must be on
@feature('tax_features') ... @else ... @endfeature {{-- effective value, escaped --}} @setting('company_name')
Flag meta and admin helpers:
Settings::feature('tax_features')->meta('owner'); Settings::feature('tax_features')->setMeta(['owner' => 'finance']); Settings::feature('tax_features')->for($user)->describe(); // effective state, source, override count, meta Settings::featureRepository()->overrideCounts(); // ['tax_features' => 12, ...] Settings::featureRepository()->overridesOf('tax_features'); // overrides with their scope models Settings::groups()->assignFeature('tax_features', 'finance');
Rules: schedule, rollout, required flags, archive
Rules belong to the flag (not to a scope) and can only turn an on flag off for some records. The order is:
- An archived flag is off everywhere, overrides included.
- A record's own override (anywhere in its scope chain) wins over every rule below.
- The global state, or the default, is the switch. If it is off, the flag is off.
- Outside the schedule window the flag is off.
- If a required flag is off for the same subject, the flag is off.
- With a rollout below 100%, only that share of records gets the flag.
$flag = Settings::feature('new_checkout'); $flag->enable()->schedule('2026-12-01 09:00', '2027-01-01'); // on from / off from (either may be null) $flag->rollout(25); // 25% of records; null for everyone $flag->requires(['new_cart']); // off unless new_cart is on too $flag->archive(); // hide it: reads as off everywhere $flag->restore(); $flag->rules(); // FeatureRules: enabledFrom, enabledUntil, rollout, requires, archivedAt $flag->updateRules(['rollout' => 50, 'requires' => []]); $flag->for($user)->explain(); // ResolvedValue: source schedule / dependency / rollout / archived, and detail
Each record gets a stable bucket (0-99) per flag, from the flag key and the record's morph class
and key: the same record always gets the same answer, and raising the percentage only adds
records. A rollout needs a subject: without one (no for() and no authenticated user) only a
100% rollout is on. Requiring an unknown flag, the flag itself or a cycle throws
InvalidSettingValueException. Rule changes fire FeatureRulesChanged and are recorded in
history (action rules), where the dashboard can revert them.
Archive a flag your code no longer checks: it leaves the dashboard lists and keeps its
overrides and history until you restore it or setanjo:sync --prune deletes it.
Set features.gate to true to use Gate::allows('feature:tax_features'). Set
features.strict to true to throw on feature keys that have no feature definition.
Metadata
Every setting can carry free-form JSON meta. The UI and validation use these keys when present; anything else is kept as-is.
| Key | Purpose |
|---|---|
unit |
Display suffix: days, %, BDT, MB |
min / max / step |
Number bounds (validated) |
input |
Editor: toggle, number, text, textarea, select, json, color, date |
options |
Allowed values for selects (validated) |
help / placeholder |
Help text |
sensitive |
Masked in history (and the dashboard) |
readonly |
Shown but not editable in the dashboard |
tags |
Labels for search and filtering |
Settings::meta('audit_retention'); // ['unit' => 'days', 'min' => 1, ...] Settings::meta('audit_retention', 'unit'); // 'days' Settings::setMeta('audit_retention', ['help' => 'Days to keep']); // merge Settings::replaceMeta('audit_retention', ['unit' => 'weeks']); // overwrite Settings::set('audit_retention', 90, meta: ['unit' => 'days']); Settings::describe('audit_retention'); // value, source, type, group, meta, ...
Effective meta is the definition's meta() merged with the meta stored in the database
(stored wins). Meta belongs to the key, not to a scope.
Groups
Group membership and order live on the global row of each setting.
$group = Settings::groups()->create(['name' => 'Mail', 'icon' => 'envelope']); Settings::groups()->update('mail', ['description' => 'Outgoing mail']); Settings::groups()->reorder(['mail', 'company', 'system']); // group order Settings::groups()->assign('smtp_host', 'mail'); // move a setting Settings::groups()->reorderSettings('mail', ['smtp_host', 'smtp_port']); // order inside a group Settings::groups()->keys('mail'); // ['smtp_host', 'smtp_port'] Settings::groups()->delete('mail'); // settings become ungrouped
Already have a groups table? Set groups_table (e.g. 'settings_group'); the migration only
adds missing columns.
Events and History
Events: SettingUpdated, SettingForgotten, SettingMetaUpdated, SettingsFlushed,
FeatureToggled, FeatureRulesChanged, SettingGroupChanged, SettingsSynced. Listen to
them for audit logs or to clear other caches.
Set history.enabled to true to record every change (value, meta, scope, causer) in
setanjo_history. Saving the value a key already has is not recorded. Flag changes store the
previous state too (FeatureToggled::$previous), so the dashboard can revert them. Values of
settings with meta sensitive => true are masked.
Dashboard
Setanjo ships a web UI at /setanjo. Host apps need no Livewire, Vue or Node: the page
inlines its prebuilt assets, so nothing has to be published and composer update never
leaves stale assets behind.
| Screen | What you can do |
|---|---|
| Overview | Counts of settings, flags (on/off, scheduled, rolling out, archived), overrides per scope type and drift issues; the latest changes; the most overridden keys |
| Settings | Edit values with editors chosen by type and meta (toggle, number + unit, select, JSON with validation, color picker, secrets); drag to reorder settings, move them between groups and reorder groups; reset to default |
| Feature flags | Set each flag's global state (default / on / off); see override counts and rule badges (starts / ends, rollout %, required flags); filter by scheduled, rolling out or archived, and restore archived flags |
| Setting / flag detail | Click any key: its value, every record that overrides it (newest first, by type), its recent changes with Revert, and copyable code (Settings::get(...), @feature(...), the route middleware). Each key has its own link (#/flags/new_checkout) to share |
| Flag rules | From the flag's detail: a schedule (date and time picker), a rollout percentage, the flags it requires, and Archive / Restore; saving can be undone and is recorded in history |
| Flag targeting | From the flag's detail: search records of any scope type and turn the flag on or off for them, or paste up to 1000 ids, preview what changes, then apply |
| Overrides | Pick a record of any configured scope type, then set or remove its flag and setting overrides; every row shows the full resolution chain (Jane: not set βΊ Acme Ltd: "daily" βΊ Global: "weekly") and which level wins, and for flags which rule decided ("Off: needs new_cart on") |
| Groups | Create, edit, delete and reorder groups |
| Meta | Edit the meta stored for a setting or flag next to the meta declared in code (key/value or raw JSON) |
| Drift | Compare definitions with the database; preview setanjo:sync, then run it |
| History | Changes grouped by day with readable diffs (JSON keys added/removed/changed), filters by key, action and scope, and Revert (when history.enabled) |
| Import / export | Download a setanjo:export file; check and import one |
Working faster:
- Search everything with Ctrl/β K: settings, flags, groups, records of every scope type, and actions such as "Turn off beta_reports". / focuses the search of the current screen, g then a letter switches screens, ? lists every shortcut.
- Undo on every save, reset and flag toggle (from the message that confirms it).
- Unsaved edits are marked; Enter saves (Ctrl Enter for JSON), Esc undoes the typing, and leaving the screen asks before dropping them.
- Light, dark or system theme; top navigation that turns into a menu on small screens.
Locked settings (is_locked) and settings with meta readonly => true cannot be changed from
the dashboard. Values with meta sensitive => true are never sent to the browser, and their
changes cannot be reverted from history (the old value is not stored).
Access
Every dashboard route (the page and its JSON API) runs through setanjo.dashboard.middleware,
the same way Telescope and Pulse work:
use Ahs12\Setanjo\Http\Middleware\Authorize; 'middleware' => ['web', Authorize::class],
Authorize (the default) lets the dashboard open in the local environment only. Elsewhere,
define a gate:
// AppServiceProvider::boot() Gate::define('viewSetanjo', fn (User $user) => $user->isAdmin());
or take full control with a callback, which wins over the gate and the environment:
use Ahs12\Setanjo\Setanjo; Setanjo::auth(fn (Request $request) => $request->user()?->isAdmin() ?? false);
Your own middleware. Add middleware to the list, or replace Authorize with it:
'middleware' => ['web', 'auth', Authorize::class], // your login + the viewSetanjo gate 'middleware' => ['web', 'auth', 'role:Super Admin'], // your middleware alone decides 'middleware' => ['web', 'auth.basic', 'can:manage-settings'],
Never public by accident. Without Authorize in the list, outside the local environment
someone must be signed in, so ['web'] alone answers 403. Set require_auth to false only when
something else protects the path (a VPN, an IP allow-list or auth at the proxy).
Changes are always checked, whatever the list: nothing in readonly mode, otherwise
Setanjo::manage() when set, else the manageSetanjo gate when defined, else whoever may view.
Gate::define('manageSetanjo', fn (User $user) => $user->isSuperAdmin()); // or Setanjo::manage(fn (Request $request) => $request->user()?->isSuperAdmin() ?? false);
Token-only APIs (Sanctum bearer tokens). A browser opening /setanjo does not send the API
token, so auth:sanctum cannot protect the page. Use a browser-friendly login instead, for
example ['web', 'auth.basic:web', 'role:Super Admin,web'] (HTTP Basic against the web guard),
a session login page, or a middleware of your own such as an IP allow-list.
Configuration
'dashboard' => [ 'enabled' => env('SETANJO_DASHBOARD_ENABLED', true), // false: no routes at all 'path' => env('SETANJO_DASHBOARD_PATH', 'setanjo'), 'domain' => env('SETANJO_DASHBOARD_DOMAIN'), 'middleware' => ['web', Authorize::class], // see Access 'require_auth' => env('SETANJO_DASHBOARD_REQUIRE_AUTH', true), 'readonly' => env('SETANJO_DASHBOARD_READONLY', false), // view only, for everyone 'brand' => [ 'title' => env('SETANJO_DASHBOARD_TITLE', 'Setanjo'), 'logo' => null, // URL or path, e.g. '/img/logo.svg' 'color' => null, // accent colour, hex: '#0ea5e9' ], 'home' => '/', // "Back to app" link (null hides it) ], // Models the Overrides screen can manage. Empty = the tenant models from tenancy_mode. 'scopes' => [ App\Models\User::class => [ 'label' => 'name', // column or fn ($user) => ... 'search' => ['name', 'email'], // columns searched with LIKE 'description' => fn ($user) => $user->email, 'without_scopes' => true, // ignore global scopes (tenant, branch) ], App\Models\Branch::class => ['search' => ['title', 'code']], ],
Any model can be a scope, not just users. On the Overrides screen you pick the type (User, Company, Branchβ¦), find a record and set overrides for it; inherited values show where they come from. Things to know:
- Label and search columns. Without
label/search, the first ofname,title,label,email,slug,codethe table has is used, and records without one show asBranch #12. Pasting an id always works: digits for integer keys, a valid UUID/ULID forHasUuids/HasUlids. - Global scopes. The dashboard queries models with their global scopes applied. If a tenant or
branch scope (one that reads the logged-in user) would hide records from the admin using the
dashboard, set
'without_scopes' => truefor that type. Opening a hidden record says so. - Soft deletes. Soft-deleted records still open (marked trashed); their overrides apply again if they are restored. They are left out of search.
- Deleted records. Overrides of a record that was deleted are listed as deleted. Opening it shows only what is stored, which can be cleared one by one or with Clear all overrides. The Drift screen lists them, and overrides stored for models the dashboard does not know.
- UUID/ULID scope models. Reading and browsing them works with the default integer id
columns (nothing can be stored for them there, so the lookups are skipped, which also keeps
Postgres from rejecting the comparison). To store overrides for them, the scope id columns
must hold their keys:
Schema::morphUsingUuids()(ormorphUsingUlids()) before the setanjo migrations run when every scope model uses them, or string id columns when integer and UUID models are mixed.
The page uses the app's CSP nonce when one is set with Vite::useCspNonce(). Alpine.js needs
'unsafe-eval' in script-src.
The UI talks to a JSON API under /setanjo/api (same middleware and access rules). Every write
goes through the package API, so validation, events, history and cache invalidation behave
exactly as in code.
HTTP API
Build your own screens on top of Setanjo: every dashboard action is also a JSON API (read and change settings and flags, per-record overrides and bulk targeting, groups, drift and sync, history and revert, import and export). It is off by default:
SETANJO_API_ENABLED=true
'api' => [ 'enabled' => env('SETANJO_API_ENABLED', false), 'prefix' => env('SETANJO_API_PREFIX', 'api/setanjo'), 'domain' => env('SETANJO_API_DOMAIN'), // Default ['api', Authorize::class]: local only, or the viewSetanjo gate. Add your clients' auth: 'middleware' => ['api', 'auth:sanctum', Authorize::class], ],
curl -H "Authorization: Bearer $TOKEN" "https://app.test/api/setanjo/features/new_checkout?scope_type=user&scope_id=42"
It needs no session or CSRF token, always answers JSON, and works with the dashboard turned
off. Read-only mode and the manageSetanjo / Setanjo::manage() rules apply to it as well.
Every endpoint, with request and response examples: docs/API.md. An OpenAPI 3.1
spec for Swagger UI, Postman or client generators: docs/openapi.yaml.
Commands
| Command | Purpose |
|---|---|
setanjo:install |
Publish config and migrations, optionally migrate |
setanjo:sync |
Sync definitions into the database (--dry-run, --prune, --reset-meta, --reset-groups, --force-types) |
setanjo:export {path?} |
Export settings, meta and groups as JSON (--global, --scope=App\Models\User:1) |
setanjo:import {path} |
Import an export (--dry-run) |
setanjo:clear-cache |
Clear cache (--all, --tenant=App\Models\User:1) |
setanjo:migrate-feature-flags |
Move flags stored as boolean settings rows into the feature tables (--key=, --keep, --dry-run) |
setanjo:install-defaults |
Deprecated: use definitions and setanjo:sync |
Caching
Enable with SETANJO_CACHE_ENABLED=true. Writes invalidate only the affected scope;
Settings::flushCache() (or setanjo:clear-cache --all) invalidates every scope at once by
bumping a version number, so it works on every cache driver. In-memory values are dropped
before each queue job and Octane request, so long-running workers see fresh values.
Common Use Cases
User Preferences
$user = auth()->user(); Settings::for($user)->set('notification_email', true); Settings::for($user)->set('dashboard_layout', 'grid'); Settings::for($user)->set('timezone', 'America/New_York');
Application Configuration
Settings::set('maintenance_mode', false); Settings::set('registration_enabled', true); Settings::set('api_rate_limit', 1000);
Multi-Tenant SaaS (Polymorphic Mode)
// Company-level settings Settings::for($company)->set('feature_api_enabled', true); Settings::for($company)->set('user_limit', 50); // User preferences within company Settings::for($user)->set('email_notifications', false);
Documentation
For detailed documentation, advanced usage, and configuration options, visit our documentation site.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
License
The MIT License (MIT). Please see License File for more information.