*/ 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::updating(function (self $model) { self::manageFields($model); }); static::deleted(function (self $model) { $model->pages()->delete(); }); static::forceDeleting(function (self $model) { $pages = $model->pages()->withTrashed()->get(); $pages->each(function ($page) { $page->forceDelete(); }); }); } // * 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); } /** * Get the target model from a specific id and model name. * * @param string $modelId * @param string $modelName * @return \Illuminate\Database\Eloquent\Model|null */ public static function getModelFromInputModelConfig( string $modelId, string $modelName, ): ?\Illuminate\Database\Eloquent\Model { $studly = Str::studly(Str::singular($modelName)); $class = "App\\Models\\{$studly}"; if (!class_exists($class)) { return null; } return $class::getModelsCached()->firstWhere('id', $modelId); } // * 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'); } }