*/ protected $fillable = [ 'type', 'title', 'subtitle', 'content', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'type' => StaticPageType::class, 'data' => 'object', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function () { throw new \RuntimeException("Creating a new page is not authorized"); }); static::updating(function (self $model) { self::assertTitleIsUnique($model->title, $model->getKey()); $model->slug = Str::slug($model->title); }); static::updated(function (self $model) { self::resetCache($model->type); }); static::deleted(function () { throw new \RuntimeException('Deleting a page is not authorized'); }); } // * ROUTABLE /** * 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'; } // * METHODS /** * Asserts using validation that the title is unique * * @param string $title * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If an actu title already exists. */ private static function assertTitleIsUnique(string $title, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id); ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id); } /** * Reset all cache elements related to this model. * * @param \App\Enums\StaticPageType $type * @return void */ private static function resetCache(StaticPageType $type): void { Cache::forget(sprintf('%sStaticPage', $type->name)); self::getCachedStaticPage($type); // Breeding pages. Cache::forget('breedingStaticPages'); } /** * Get cached static page associated to a given type. * * @param \App\Enums\StaticPageType $type * @return \App\Models\StaticPage */ public static function getCachedStaticPage(StaticPageType $type): \App\Models\StaticPage { return Cache::rememberForever( sprintf('%sStaticPage', $type->name), fn() => self::query()->where('type', $type)->first() ); } }