Skip to content

TheDragonCode/laravel-model-settings

Repository files navigation

Laravel Model Settings

Laravel Model Settings

Stable Version Total Downloads License

Persist shared defaults and per-model overrides for Eloquent models.

Laravel Model Settings keeps configurable values outside your model tables. Define a default once, override it for individual records, and read the effective value through one API.

Requires PHP 8.3+ and Laravel 12 or 13.

Key Features

  • Shared defaults are isolated by Eloquent model class.
  • Per-model values override defaults without changing other records.
  • get(), has(), and all() resolve shared defaults and per-model overrides automatically.
  • set() and setMany() preserve exact JSON values, including null, empty strings, and arrays.
  • forgetMany() and purge() provide bounded-query deletion for explicit scopes.
  • Eager loading avoids one settings query per model in a collection.
  • Integer, string, UUID, and ULID primary keys work with or without a Laravel morph map, including persisted integer 0 and string '0' identifiers.
  • Payloads use JSON by default and may use model-wide or per-key custom casts.

Quick Start

composer require dragon-code/laravel-model-settings

php artisan vendor:publish --tag="model_settings"
php artisan migrate

Example

Add the trait to an Eloquent model:

use DragonCode\LaravelModelSettings\Concerns\HasSettings;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasSettings;
}

Set a shared default, override it for a saved model, and read the effective value:

(new User)->defaultSettings()->set('timezone', 'UTC');

$user->settings()->set('timezone', 'Europe/Paris');
$user->settings()->setMany([
    'locale' => 'fr',
    'notifications.email' => true,
]);

assert($user->settings()->get('timezone') === 'Europe/Paris');
assert($user->settings()->has('notifications.email'));

$user->settings()->forget('timezone');

assert($user->settings()->get('timezone') === 'UTC');

Package Scope

This package deliberately stays database-backed and model-scoped. It does not provide Redis or model-field storage, a repository registry, typed global settings discovery, a per-key migration runner, a mandatory cross-request cache, or a second defaults table.

Documentation

Read the documentation site or open a guide in the repository:

Guide Description
Overview Resolution rules, boundaries, and supported models
Getting Started Installation and first setting
Working with Settings Defaults, owners, keys, and JSON values
Eager Loading Avoiding settings N+1 queries
Configuration Connection, schema, and storage model
Payload Casts JSON, custom casts, and data objects
API Reference Public methods and return values
Development Tests, documentation, and security

License

The MIT License (MIT). See License File.