*/ 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. * * @return void */ protected static function booted(): void { static::creating(function (self $newsClub) { self::assertTitleIsUnique($newsClub->title); self::manageFields($newsClub); }); static::updating(function (self $newsClub) { self::assertTitleIsUnique($newsClub->title, $newsClub->getKey()); self::manageFields($newsClub); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); }); } // * METHODS /** * Manage model fields. * * @param self $model * @return void */ 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 * * @param string|null $title * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If an news category 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); } // * RELATIONSHIPS /** * Get all survey answers of the news club (survey type). * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function answers(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(SurveysAnswer::class); } }