*/ 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::creating(function (self $model) { self::manageFields($model); }); static::created(function () { self::resetCache(); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { self::resetCache(); }); static::deleted(function (self $model) { $model->pages()->delete(); self::resetCache(); }); static::restored(function () { self::resetCache(); }); static::forceDeleting(function (self $model) { $pages = $model->pages()->withTrashed()->get(); $pages->each(function ($page) { $page->forceDelete(); }); }); static::forceDeleted(function () { self::resetCache(); }); } // * METHODS /** * Manage model fields. * * @param self $model * @return void * @throws \Illuminate\Validation\ValidationException Label already used. */ private static function manageFields(self $model): void { // Check unique fields. $label = $model->label; TranslationHelper::assertTranslationFieldIsUnique( model: $model, value: $label, dbAttribute: 'label', errorTranslation: trans('validation.custom.label') ); $model->setAttribute('label', $label); // Check translations. TranslationHelper::validateFallbackTranslations($model); } /** * 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; } /** * Reset all cache elements related to this model. * * @return void */ public static function resetCache(): void { Cache::forget('publishedPageConfigs'); self::getPublishedPageConfigs(); } /** * Get all published dynamic pages. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getPublishedPageConfigs(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('publishedPageConfigs', 86400, function () { return self::query() ->with('pages') ->get(); }); } // * 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'); } }