mrdth/laravel-model-settings

Easy to use way to add settings to any Eloquent model

v1.1.0 2024-07-27 21:48 UTC

This package is auto-updated.

Last update: 2024-10-27 22:20:57 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package utilizes Eloquents JSON casting to provide a simple way to add settings to any Eloquent model.

Installation

You can install the package via composer:

composer require mrdth/laravel-model-settings

You can publish the config file with:

php artisan vendor:publish --tag="laravel-model-settings-config"

This is the contents of the published config file:

return [
    'column' => env('MRDTH_MODEL_SETTINGS_COLUMN_NAME', 'settings'),
];

Usage

Migrations

First add the settings column to your model's migration.

...
    $table->json('settings')->nullable();
...

For existing models you can create a migration using our artisan command.

php artisan make::msm {model}

To change the column used for settings you can update the MRDTH_MODEL_SETTINGS_COLUMN_NAME in your .env file.

Models

Next add the HasSettings trait to any Eloquent model you want to have settings.

...
use Illuminate\Notifications\Notifiable;
use Mrdth\LaravelModelSettings\Concerns\HasSettings;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasSettings;
...

Using the model settings

Once the trait is added you can interact with the settings using methodsL

$user = User::find(1);
$user->hasSetting('use custom avatar'); // false

$user->setSetting('use custom avatar', true);
$user->hasSetting('use custom avatar'); // true
$user->getSetting('use custom avatar'); // true

$user->updateSetting('use custom avatar', false);
$user->getSetting('use custom avatar'); // false
$user->getSetting('non-existent setting'); // null
$user->getSetting('non-existent setting', 'default value'); // 'default value'

$user->getSettings(); // ['use custom avatar' => false]

$user->deleteSetting('use custom avatar');
$user->hasSetting('use custom avatar'); // false

$user->deleteSettings();

Query Scopes

You can also query models based on their settings.

$users = User::whereSetting('use custom avatar')->get(); // Returns all users with the setting 'use custom avatar'
$users = User::whereSetting('use custom avatar', true)->get(); // Returns all users with the setting 'use custom avatar' set to true

Testing

composer tests

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

License

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