moirei / settings
A simple solution for application settings.
Requires
- php: ^8.0
- illuminate/contracts: ^7|^8|^9
- illuminate/support: ^7|^8|^9
- laravel/helpers: ^1.5
- moirei/fields: ^1.1
Requires (Dev)
- illuminate/contracts: ^7|^8|^9
- orchestra/testbench: ^7.5
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.2
- phpunit/phpunit: ^9.5
- thled/pest-plugin-shorthands: ^1.1
This package is auto-updated.
Last update: 2025-03-10 07:54:40 UTC
README
This package is a simple approach to managing Eloquent model settings.
This package currently does not support managing global app settings.
$notificationsEnabled = $user->settings->get('notifications.enable');
Installation
composer require moirei/settings
Publish the config
php artisan vendor:publish --tag="model-settings"
Usage
Cast attributes
The simplest way to use the with a model is casting to the settings collection.
use MOIREI\Settings\AsSettingsCollection; use MOIREI\Fields\Inputs\Boolean; ... class User extends Model{ ... protected $casts = [ 'settings' => AsSettingsCollection::class, ]; /** * Get settings configuration (optional) * * @return array */ public function settingsConfig(): array { return [ 'notifications.enable' => Boolean::make('Enable notification')->default(false), ]; } }
New user models with empty settings should have defauls.
$user = new User(); $notificationsEnabled = $user->settings->get('notifications.enable'); // Or provide a prefered default $notificationsEnabled = $user->settings->get('notifications.enable', true);
Directly access settings values
$notifications = $this->model->settings->notifications; expect($notifications)->toBeArray();
Has settings trait
For a more function approach to accessing settings, ascribe the HasSettings
trait to your model.
This trait also provides a default settingsConfig
method that resolves defaults from settings.php
config. E.g. the User
model will expect defaults in defaults.users
of your config.
use MOIREI\Settings\HasSettings; ... class User extends Model{ use HasSettings; ... }
$user = new User(); expect($user->settings())->toBeCollection(); expect($user->settings('notifications.enable'))->toBeBool();
Reusable settings
You can reusable settings
class UserSettings extends Settings { /** * @inheritdoc */ public function fields(): array { return [ 'notifications.enable' => Boolean::make('Enable notification')->default(false) ]; } }
Update in config
// config/settings.php 'groups' => [ 'users' => \App\Settings\UserSettings::class, ],
Now your model can be pointed to the config.
class User extends Model{ use HasSettings; // optional if lower-cased pluralised form of class name matches name in groups protected $settingsConfig = 'users'; }
Tests
composer test