Skip to main content

← Overview · Back to README · Working with Settings →

Getting Started

Requirements​

  • PHP 8.3 or newer.
  • Laravel 12 or 13.

Install the package​

composer require dragon-code/laravel-model-settings

Laravel discovers the package service provider automatically.

Publish the configuration and migration, then create the settings table:

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

The model_settings tag publishes both config/model_settings.php and the package migration. The default migration creates a settings table on the application's default database connection.

Add the trait​

Add HasSettings to every Eloquent model that needs settings:

namespace App\Models;

use DragonCode\LaravelModelSettings\Concerns\HasSettings;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use HasSettings;
}

The trait adds this public surface:

MemberUse
settings()Read or change effective settings for one saved model
defaultSettings()Read or change defaults for the model class
modelSettings()Eloquent relation used for eager loading

Store the first setting​

Create a default for all saved User models:

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

Override that value for one saved user:

$user = User::query()->firstOrFail();

$user->settings()->set('timezone', 'Europe/Paris');

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

Read all effective settings as a collection keyed by setting name:

$settings = $user->settings()->all();

assert($settings->get('timezone') === 'Europe/Paris');

Remove the override to fall back to UTC:

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

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

Persist models first​

Use settings()->set(), setMany(), forget(), forgetMany(), and purge() only after the parent model has been saved. For an unsaved model, settings()->get() returns null, settings()->has() returns false, and settings()->all() returns an empty collection even when class defaults exist. Every mutation method throws DragonCode\LaravelModelSettings\Exceptions\InvalidSettingsOwnerException before a storage query runs.

See Also​