This repository was archived by the owner on Apr 20, 2022. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +55
-13
lines changed Expand file tree Collapse file tree 2 files changed +55
-13
lines changed Original file line number Diff line number Diff line change @@ -77,6 +77,37 @@ $user->settings()->forget('some.setting');
77
77
```
78
78
79
79
##### 6.) Set the default settings for a new model.
80
+
81
+ If you define ` $defaultSettings ` as an array property on your model, we will use its value as the default settings for
82
+ any new models that are created * without* settings.
83
+
84
+ _ User.php_
85
+ ```
86
+ use Cklmercer\ModelSettings\HasSettings;
87
+ use Illuminate\Foundation\Auth\User as Authenticatable;
88
+
89
+ class User extends Authenticatable
90
+ {
91
+ use HasSettings;
92
+
93
+ /**
94
+ * The model's default settings.
95
+ *
96
+ * @var array
97
+ */
98
+ protected $defaultSettings = [
99
+ 'homepage' => '/profile'
100
+ ];
101
+
102
+ // truncated for brevity..
103
+ }
104
+ ```
105
+
106
+ ##### 7.) Specify the settings that are allowed.
107
+
108
+ If you define ` $allowedSettings ` as an array property then only settings which match a value within
109
+ the ` $allowedSettings ` array will be saved on the model.
110
+
80
111
_ User.php_
81
112
```
82
113
use Cklmercer\ModelSettings\HasSettings;
@@ -87,18 +118,11 @@ class User extends Authenticatable
87
118
use HasSettings;
88
119
89
120
/**
90
- * Set the model's default settings.
91
- *
92
- * @return void
121
+ * The model's allowed settings.
122
+ *
123
+ * @var array
93
124
*/
94
- protected function setDefaultSettings()
95
- {
96
- $this->settings = [
97
- 'some' => [
98
- 'setting' => true
99
- ]
100
- ];
101
- }
125
+ protected $allowedSettings = ['homepage'];
102
126
103
127
// truncated for brevity..
104
128
}
Original file line number Diff line number Diff line change @@ -12,10 +12,28 @@ trait HasSettings
12
12
public static function bootHasSettings ()
13
13
{
14
14
self ::creating (function ($ model ) {
15
- if (method_exists ( $ model, ' setDefaultSettings ' ) ) {
16
- $ model ->setDefaultSettings ();
15
+ if ( ! $ model-> settings ) {
16
+ $ model ->settings = $ model -> getDefaultSettings ();
17
17
}
18
18
});
19
+
20
+ self ::saving (function ($ model ) {
21
+ if (property_exists ($ model , 'allowedSettings ' ) && is_array ($ model ->allowedSettings )) {
22
+ $ model ->settings = array_only ($ model ->settings , $ model ->allowedSettings );
23
+ }
24
+ });
25
+ }
26
+
27
+ /**
28
+ * Get the model's default settings.
29
+ *
30
+ * @return array
31
+ */
32
+ public function getDefaultSettings ()
33
+ {
34
+ return (isset ($ this ->defaultSettings ) && is_array ($ this ->defaultSettings ))
35
+ ? $ this ->defaultSettings
36
+ : [];
19
37
}
20
38
21
39
/**
You can’t perform that action at this time.
0 commit comments