moirei/settings

A simple solution for application settings.

1.2.0 2022-09-10 02:29 UTC

This package is auto-updated.

Last update: 2024-04-10 05:38:54 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