65

GitHub - rennokki/eloquent-settings: Eloquent Settings is a package that binds k...

 5 years ago
source link: https://github.com/rennokki/eloquent-settings
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

readme.md

Build Status codecov StyleCI Latest Stable Version Total Downloads Monthly Downloads License

PayPal

Laravel Eloquent Settings

Eloquent Settings is a small helper to bind key-value pairs to your models.

Installation

Install the package:

$ composer require rennokki/eloquent-settings

If your Laravel version does not support package discovery, add the following line in the providers array in the config/app.php file:

Rennokki\Settings\SettingsServiceProvider::class,

Publish the config file & migration files:

$ php artisan vendor:publish

Migrate the database:

$ php artisan migrate

Then you can add the HasSettings trait to your Eloquent model:

use Rennokki\Settings\Traits\HasSettings;

class User extends Model {
    use HasSettings;
    ...
}

Adding settings

$user->newSetting('subscribed.to.newsletter', 1);
$user->newSetting('subscribed.to.newsletter', true);

By default, settings' values are stored as string. Don't worry, later, if you try to get them with cast, they will return the value you have initially stored. If you store 'true' as a string, if you cast it to a boolean, you'll get true.

If you plan to store it with cast type other than string, you can pass an additional third parameter that can be either string, boolean, bool, int, integer, float or double.

$user->newSetting('subscribed.to.newsletter', true, 'bool');

Updating settings

Updating settings can be either to values, cast types or both.

$user->updateSetting('subscribed.to.newsletter', false, 'bool');

If you don't specify a cast parameter, it will not change, only the value will change.

Getting settings & values

You can get the Setting instance, not the value.

$user->getSetting('subscribed.to.newsletter'); // does not accept a cast

If you plan to get the value, you can use:

$user->getSettingValue('subscribed.to.newsletter'); // true, as boolean
$user->getSettingValue('subscribed.to.newsletter', 'int'); // 1, as integer

Remember, when you update or create a new setting, the cast type is stored. Next time, you don't have to call the cast parameter again.

Getting values of not-known settings keys, you will receive null.

$user->getSettingValue('subscribed.to.weekly.newsletter'); // null

Deleting settings

Deleting settings from the database can be done using deleteSetting().

$user->deleteSetting('subscribed_to_newsletter');

To delete all settings, call deleteSettings().

$user->deleteSettings();

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK