*/ protected $fillable = [ 'type', 'title', 'slug', 'content', 'picture', 'picture_title', 'picture_alt', 'multiple_answers', 'published', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'type' => NewsClubTypeEnum::class, 'multiple_answers' => 'boolean', 'published' => 'boolean', 'publish_at' => 'datetime', 'unpublish_at' => 'datetime', ]; /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $newsClub) { self::assertTitleIsUnique($newsClub->title); self::manageFields($newsClub); }); static::created(function () { self::resetCache(); }); static::updating(function (self $newsClub) { self::assertTitleIsUnique($newsClub->title, $newsClub->getKey()); self::manageFields($newsClub); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); self::resetCache(); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); self::resetCache(); }); } // * METHODS /** * Manage model fields. */ private static function manageFields(self $model): void { $model->slug = Str::slug($model->title); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); } /** * Asserts using validation that the title is unique. * * @throws \Illuminate\Validation\ValidationException If an news category 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. */ private static function resetCache(): void { Cache::forget('publishedNewsClubOrderedByPublishAt'); self::getPublishedOrderedByPublishAt(); } /** * Get all published news with categories relations. */ public static function getPublishedOrderedByPublishAt(): Collection { return Cache::remember('publishedNewsClubOrderedByPublishAt', 86400, function () { return self::query()->where('published', true)->orderBy('publish_at', 'asc')->take(3)->get(); }); } // * RELATIONSHIPS /** * Get all survey answers of the news club (survey type). */ public function answers(): HasMany { return $this->hasMany(SurveysAnswer::class); } }