Laravel Model Settings

News

July 11th, 2019

global-settings-featured.png

Laravel Model Settings is a package by Lorand Gombos to provide model settings configuration in a database field or a separate database table.

The package ships with two traits—settings in a field or table—that you can configure in a given model (one or the other, not both). First, the settings field is a JSON field:

1// Settings field
2
3use Glorand\Model\Settings\Traits\HasSettingsField;
4
5class User extends Model
6{
7 use HasSettingsField;
8
9 //define only if you select a dirrerent name from the default
10 public $settingsFieldName = 'user_settings';
11
12}

And a separate settings table option:

1use Glorand\Model\Settings\Traits\HasSettingsTable;
2
3class User extends Model
4{
5 use HasSettingsTable;
6}

Here’s some basic usage examples in a model:

1// Get all settings
2$user->settings()->all();
3
4// Get a specific setting
5$user->settings()->get('some.setting');
6$user->settings()->get('some.setting', 'default value');
7
8// Add/Update
9$user->settings()->apply((array)$settings);
10$user->settings()->set('some.setting', 'new value');
11$user->settings()->update('some.setting', 'new value');
12
13// Remove
14$user->settings()->delete('some.setting');

You can learn more about this package, get full installation instructions, and view the source code on GitHub at glorand/laravel-model-settings.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.