diff --git a/src/Models/AppSetting.php b/src/Models/AppSetting.php index 91e8f324d..bb8a4c6d7 100644 --- a/src/Models/AppSetting.php +++ b/src/Models/AppSetting.php @@ -26,6 +26,19 @@ class AppSetting extends Model private bool $didRegisterSettingsBlocks = false; + public static function booted() + { + self::saving(function (self $model) { + /* + * Here we remove the 'blocks' relation so that any developer hooking + * into the saved event on the AppSetting can still fetch the settings + * with the new values. The next time the setting facade is called to + * retrieve a setting, the blocks relation is hydrated again. + */ + $model->unsetRelation('blocks'); + }); + } + /** * @return array|array */ diff --git a/src/Services/Settings/SettingsGroup.php b/src/Services/Settings/SettingsGroup.php index 63701a016..2707995b4 100644 --- a/src/Services/Settings/SettingsGroup.php +++ b/src/Services/Settings/SettingsGroup.php @@ -18,6 +18,8 @@ class SettingsGroup private ?Closure $availableWhen = null; + private AppSetting $appSetting; + public static function make(): self { return new self(); @@ -70,12 +72,9 @@ public function hasSection(string $sectionName): bool public function getSettingsModel(): AppSetting { - $settingsModel = AppSetting::where(['name' => $this->getName()])->first(); - if (!$settingsModel) { - $settingsModel = AppSetting::create(['name' => $this->getName()]); - } - - return $settingsModel; + return $this->appSetting ??= AppSetting::firstOrCreate([ + 'name' => $this->getName(), + ]); } /** diff --git a/src/TwillAppSettings.php b/src/TwillAppSettings.php index 32de3b73f..17efa6bef 100644 --- a/src/TwillAppSettings.php +++ b/src/TwillAppSettings.php @@ -105,7 +105,7 @@ public function getGroupDataForSectionAndName(string $group, string $section): B { $groupObject = $this->getGroupForGroupAndSectionName($group, $section); - return $groupObject->getSettingsModel()->blocks() + return $groupObject->getSettingsModel()->blocks ->where('editor_name', $section) ->where('parent_id', null) ->firstOrFail(); diff --git a/tests/integration/Settings/SettingsFacadeTest.php b/tests/integration/Settings/SettingsFacadeTest.php index 2e4ffb640..d677d1e7d 100644 --- a/tests/integration/Settings/SettingsFacadeTest.php +++ b/tests/integration/Settings/SettingsFacadeTest.php @@ -5,6 +5,7 @@ use A17\Twill\Exceptions\Settings\SettingsGroupDoesNotExistException; use A17\Twill\Exceptions\Settings\SettingsSectionDoesNotExistException; use A17\Twill\Facades\TwillAppSettings; +use A17\Twill\Models\AppSetting; use A17\Twill\Services\Settings\SettingsGroup; use A17\Twill\Tests\Integration\TestCase; @@ -66,6 +67,9 @@ public function setUp(): void ] ) ->assertStatus(200); + + /** @see AppSetting::booted() */ + $model->unsetRelation('blocks'); } public function testTranslatedSettingsGetter(): void