Strongly typed settings for Laravel, includes built-in encryption and friendly validation.

Overview

run-tests codecov

Strongly Typed Laravel Settings

Install

composer require bogdankharchenko/typed-laravel-settings

Model Setup

namespace App\Models\User;

use Illuminate\Database\Eloquent\Model;
use BogdanKharchenko\Settings\Models\HasSettings;

class User extends Model
{
    use HasSettings;    
}

Creating a Setting Class

This class represents a group of available settings for a given model. Public properties and their values will automatically be serialized into a json column, and serve as defaults.

use BogdanKharchenko\Settings\BaseSettings;

class UserSettings extends BaseSettings
{
    public string $favoriteColor = 'red';
}

Set Settings

Changing the values will persist them into the database. When updating settings, cache will automatically be flushed.

$user = User::first();

$user->setSettings(function(UserSettings $settings){
    $settings->favoriteColor = 'blue';
});

// Updating Multiple Settings

$user->setSettings(function(UserSettings $settings, EmailPreferences $emailPreferences){
    $settings->favoriteColor = 'blue';

    $emailPreferences->marketing = false;
});

// Using the `setSettings()` Closure is a wrapper around the code example below.
$settings = new UserSettings($user);

$settings->favoriteColor = 'pink';

$settings->saveSettings();

Get Settings

Creating a helper function on your allows us to access strongly typed settings. When a setting is retrieved from the database, it will overwrite the default setting on the class.

class User extends Model 
{
    public function config(): UserSettings
    {
        return new UserSettings($this);      
    }
}

$user->config()->favoriteColor // returns blue

// Alternatively you can use docblocks to assist in typing

/** @var UserSettings $settings */
$settings = $user->getSettings(UserSettings::class);

$settings->favoriteColor // returns blue

Setting Value Encryption

You may decide to encrypt/decrypt sensitive settings such as secrets. You should specify a protected array $encrypted with a list of properties to encrypt/decrypt. Data will be encrypted into the database, and decrypted when retrieved.

use BogdanKharchenko\Settings\BaseSettings;

class UserSettings extends BaseSettings
{
    protected array $encrypted = [
        'secret',
        'list',
    ];

    public ?string $secret = null;

    public array $list = [
        'a',
        'b',
        'c',
    ];
}

The default encrypter is BogdanKharchenko\Settings\Repository\Encrypter but you may choose to implement your own encryption strategy by implementing BogdanKharchenko\Settings\Contracts\EncrypterInterface and changing the config.

Validation

You can define validation rules in your custom Settings class, in the same way as you would in FormRequests using the rules() and messages() methods. These rules will be triggered immediately before attempting to persist the data into the database.

class SimpleSettingWithRule extends BaseSettings
{
    public string $favoriteColor = 'red';

    // Optional
    public function rules()
    {
        return [
            'favoriteColor' => ['required', Rule::in(['red', 'green'])],
        ];
    }

    // Optional 
    public function messages()
    {
        return [
            'favoriteColor.in' => 'color does not match',
        ];
    }
}

Validation is optional, as you may choose to do this in other parts of your app. You can also customize the validator by implementing the BogdanKharchenko\Settings\Contracts\ValidatorInterface and changing the validator config.

Morph Map & Caching

Similarly to morph map for Eloquent, it is a good idea to allow your Setting be more flexible to restructuring without touching your database.

// config/typed-settings.php

return [
    'morph'=>[
        'user-settings'=> UserSettings::class,
    ],
    'cache' => [
        'enabled' => true,
        'store' => 'redis',
        'seconds' => 600,
    ],
    
   'encrypter' => \BogdanKharchenko\Settings\Repository\Encrypter::class,
   'validator' => \BogdanKharchenko\Settings\Repository\Validator::class,
];

Scopes

Sometimes you may need to check a setting on a database level, there is a helper scope available.

$users = User::query()
    ->whereSettings(UserSettings::class, 'favoriteColor', 'blue')
    ->get();
You might also like...
This Laravel Nova settings tool based on env, using nativ nova fields and resources
This Laravel Nova settings tool based on env, using nativ nova fields and resources

Nova Settings Description This Laravel Nova settings tool based on env, using nativ nova fields and resources Features Using native Nova resources Ful

Persistent settings in Laravel

Laravel Settings Persistent, application-wide settings for Laravel. Despite the package name, this package works with Laravel 4, 5, 6, 7 and 8! Common

Per-user settings repository system for Laravel
Per-user settings repository system for Laravel

Laraconfig Per-user settings repository system for Laravel. This package allows users to have settings that can be queried, changed and even updated,

Add settings to any Laravel model.

Laravel Property Bag Simple settings for Laravel apps. Easily give multiple resources settings Simple to add additional settings as your app grows Set

Model Settings for your Laravel app
Model Settings for your Laravel app

Model Settings for your Laravel app The package requires PHP 7.3+ and follows the FIG standards PSR-1, PSR-2, PSR-4 and PSR-12 to ensure a high level

Friendly prefixed IDs for Laravel models
Friendly prefixed IDs for Laravel models

Friendly prefixed IDs for Laravel models Prefixing an id will help users to recognize what kind of id it is. Stripe does this by default: customer ids

Store your Laravel application settings in an on-disk JSON file

Store your Laravel application settings in an on-disk JSON file. This package provides a simple SettingsRepository class that can be used to store you

An interface for the administrator to easily change application settings. Uses Laravel Backpack
An interface for the administrator to easily change application settings. Uses Laravel Backpack

Backpack\Settings An interface for the administrator to easily change application settings. Uses Laravel Backpack. Works on Laravel 5.2 to Laravel 8.

PHP implementation of Nanoid, secure URL-friendly unique ID generator

Nanoid-php A tiny (179 bytes), secure URL-friendly unique string ID generator for JavaScript Safe. It uses cryptographically strong random APIs and gu

Releases(v1.0.0)
Bootstrap Theme Generator inside of a Wordpress-Settings-Page. Includes live compilation of SCSS!

Bootstrap-Theme-Generator Bootstrap Theme Generator enables you to choose which components of Bootstrap you want to load. It also gives you the possib

null 3 Aug 15, 2022
Simple Video is a automated H264 encryption system built on Lumen Laravel Framework

Simple Video is a automated H264 encryption system built on Lumen Laravel Framework

Azril Nazli Alias 4 Oct 5, 2022
Generate random typed values and in any shape.

PHP Typed Generators Description Generate random typed values and in any shape. Useful for writing your tests, there's no need to write static set of

(infinite) loophp 2 Jun 8, 2022
⚙️Laravel Nova Resource for a simple key/value typed setting

Laravel Nova Resource for a simple key/value typed setting Administer your Laravel Simple Setting in Nova Pre-requisites This Nova resource package re

elipZis 5 Nov 7, 2022
Laravel Ajax Datatable is a nice laravel admin panel which includes authentication, CRUD and Ajax datatable.

Laravel Ajax Datatable is a nice laravel admin panel which includes authentication, CRUD and Ajax datatable. the datatable is created with laravel & ajax so No need to install another package, yout can do search, sort, paginate and show records per page fastly.

Jumah 3 Oct 3, 2022
Encryption cast for Eloquent

Encrypted A custom cast class for Laravel Eloquent that encrypts or hashes your values. Package is small and provides just a few, simple, well tested

null 58 Oct 1, 2022
Library to intercept PHP includes

Library to intercept and dynamically transform PHP includes. Forked from icewind1991/interceptor.

Nikita Popov 68 Sep 15, 2022
Create a downloads list - quick and easy. With categories and mobile friendly design

Simple downloads list plugin for wordpress Create a downloads list - quick and easy. With categories and mobile friendly design What is Simple downloa

Neofix 2 Dec 4, 2022
Store and retrieve settings generally or for model objects in Laravel.

Store and retrieve settings generally or for model objects in Laravel. Documentation You can find the detailed documentation here in Laravel Settings

Pharaonic 7 Dec 19, 2022
Simple Arabic Laravel Dashboard , has basic settings and a nice layout . to make it easy for you to create fast dashboard

Simple Arabic Laravel Dashboard ✅ Auto Seo ✅ Optimized Notifications With Images ✅ Smart Alerts ✅ Auto Js Validations ✅ Front End Alert ✅ Nice Image V

Peter Tharwat 254 Dec 19, 2022