Settings
Settings are similar to preferences, however settings are more system oriented, and are only applied per Tenant. Settings also have impact on specific components, and typically require specific permissions to be updated.
Creating a Setting
Settings are defined in config/components.php
.
Let's add a 2fa_required
setting for the authentication
component:
return [
...
'authentication' => [
...
'2fa_required' => [
'default' => false,
'items' => [
[
'id' => true,
'label' => 'Yes'
],
[
'id' => false,
'label' => 'No'
],
]
],
]
];
Each module has it's own routes and {Module}SettingsController
controllers because they might drastically differ from
eachother.
For reference, this is the AuthenticationSettingsController
:
class AuthenticationSettingsController extends Controller
{
use HasFields;
public function form(): JsonResponse
{
$this->checkPermission();
return $this->fieldsResponse($this->fields());
}
public function update(Request $request): JsonResponse
{
$this->checkPermission();
$validated = $this->validateFields($request, $this->fields());
foreach ($validated as $field => $value) {
auth()->user()->tenant->setSetting('authentication', $field, $value);
}
return response()->json([
'message' => 'ok'
]);
}
private function checkPermission()
{
abort_unless(auth()->user()->hasPermissionScope(SettingsManagement::class), 403);
}
private function fields(): FieldCollection
{
return new FieldCollection(
SettingSelect::make(__('2FA required for everyone'), '2fa_required')
->forComponent('authentication')
->default(setting('authentication', '2fa_required'))
);
}
}
Usage
Backend
To retrieve a setting:
$value = setting('authentication', '2fa_required');
To set a setting:
auth()->user()->tenant->setSetting('authentication', '2fa_required', false);
Front-end
To retrieve a setting:
this.$setting('authentication', '2fa_required')