*/ protected $fillable = [ 'label', 'view', 'config', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'config' => 'array', ]; /** * The translatable columns. * * @var list */ public $translatable = [ 'label', 'config', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::updated(function (self $model) { /** * If the config is updated, delete the content of all associated dynamic pages * because of potentials breaking errors and set the status to draft. */ $oldConfig = $model->getOriginal('config'); if (isset($oldConfig[config('app.locale')])) { $oldConfig = $oldConfig[config('app.locale')]; if (!self::isConfigUpdated($model->config, $oldConfig)) { $model->pages->map(function (DynamicPage $dynamicPageModel) { $dynamicPageModel->content = ""; $dynamicPageModel->status = PageStatusEnum::draft; $dynamicPageModel->saveOrFail(); }); } } }); static::deleting(function (self $model) { $model->pages()->delete(); }); static::restoring(function (self $model) { $model->pages()->withTrashed()->restore(); }); } /** * Check if the config is updated. * * @param array $newArray * @param array $originalArray * @return boolean */ private static function isConfigUpdated(array $newArray, array $originalArray): bool { if (count($newArray) !== count($originalArray)) { return false; } foreach ($newArray as $i => $subA) { $subB = $originalArray[$i] ?? null; if ($subB === null) { return false; } ksort($subA); ksort($subB); if ($subA != $subB) { return false; } } return true; } // * RELATIONSHIPS /** * Get pages for the config. * * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\DynamicPage,$this> */ public function pages(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(DynamicPage::class, 'config_id'); } }