*/ protected $fillable = [ 'seo_title', 'seo_description', 'title', 'content', 'picture', 'picture_alt', 'picture_title', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'type' => StaticPageType::class, ]; /** * 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::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); }); } // * METHODS. /** * Get the value of the model's route key. * * @return mixed */ public function getRouteKey(): mixed { /** @var \App\Enums\StaticPageType */ $enum = $this->getAttribute($this->getRouteKeyName()); return $enum->value(); } /** * Get the route key for the model. * * ! Type is the routable parameter * * @return string */ public function getRouteKeyName(): string { return 'type'; } /** * Manage model fields. * * @param self $model * @return void */ private static function manageFields(self $model): void { // * ASSERTIONS self::assertTitleIsUnique($model->title, $model->id); if ($model->content) { ToolboxHelper::assertNoInternalBoUrls('content', $model->content); $model->content = clean($model->content); } if ($model->picture) { $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); } // * TRANSFORMATIONS self::setSlug($model, $model->title); } /** * Set the slug. * * @param self $model * @param string $original * * @return void */ private static function setSlug(self $model, string $original): void { $model->slug = Str::slug($original); } /** * Asserts using validation that the title is unique * * @param string|null $title * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If an actu title already exists. */ private static function assertTitleIsUnique(string|null $title, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id); ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id); } /** * Returns the static page for a page type. * * @param \App\Enums\StaticPageType $type * @return \App\Models\StaticPage */ public static function getStaticPage(StaticPageType $type): \App\Models\StaticPage { $query = (new self())->where('type', $type)->first(); return $query; } // * RELATIONS. /** * * * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Section,$this> */ public function sections(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Section::class, 'page_id'); } }