mrdth / laravel-model-settings
Easy to use way to add settings to any Eloquent model
Fund package maintenance!
mrdth
Requires
- php: ^8.2
- illuminate/contracts: ^10.0||^11.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.14
- mockery/mockery: ^1.6
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^9.0.0||^8.22.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-arch: ^2.7
- pestphp/pest-plugin-laravel: ^2.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
README
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.