signifly/laravel-configurable

Make your Eloquent models configurable.

v1.5.0 2021-03-29 08:29 UTC

This package is auto-updated.

Last update: 2024-03-29 03:50:51 UTC


README

Latest Version on Packagist Tests StyleCI Quality Score Total Downloads

The signifly/laravel-configurable package allows you to easily make your Eloquent models configurable.

Below is a small example of how to use it.

// Remember to add use statement
use Signifly\Configurable\Configurable;

class User
{
    use Configurable;
    
    // Remember to make `config` fillable
    protected $fillable = [
        'config',
    ];
    
    // Remember to add `config` to casts
    protected $casts = [
        'config' => 'array',
    ];
}

Adding the column to your table migration:

Schema::table('users', function (Blueprint $table) {
    $table->json('config')->nullable();
});

Now you would be able to configure your user model:

$user = User::find(1);
$user->config()->some_key = 'some val';
$user->config()->set('some_other_key', 'some other val');
$user->save();

Retrieving from your config is straightforward:

$user = User::find(1);
$user->config()->some_key; // returns some val
$user->config()->get('some_other_key'); // return some other val

Removing attributes from config can be done like this:

$user = User::find(1);
$user->config()->remove('some_key');
$user->save();

Checking if an attribute exists in the config:

$user = User::find(1);
$user->config()->has('some_key'); // returns true

Retrieving an attribute as a collection:

$user = User::find(1);
$user->config()->collect('some_key'); // returns Collection(['some val']);

You can also overwrite the config key:

// Remember to add use statement
use Signifly\Configurable\Configurable;

class User
{
    use Configurable;
    
    // Remember to make `settings` fillable
    protected $fillable = [
        'settings', 'extras',
    ];
    
    // Remember to add `settings` to casts
    protected $casts = [
        'settings' => 'array',
        'extras' => 'array',
    ];

    protected function getConfigKey()
    {
        return 'settings';
    }

    // or add a custom config attribute like this:
    public function getExtrasAttribute()
    {
        return new Config($this, 'extras');
    }
}

Documentation

Until further documentation is provided, please have a look at the tests.

Installation

You can install the package via composer:

$ composer require signifly/laravel-configurable

The package will automatically register itself.

Testing

$ composer test

Security

If you discover any security issues, please email dev@signifly.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.