*/ protected $fillable = [ 'title', 'content', 'picture', 'picture_alt', 'picture_title', 'category_id', 'page_id', ]; /** * Validates that the maximum number of sections has not been exceeded. * * @throws \Exception If the maximum number of sections has been exceeded. */ protected function validateMaxSectionCount(): void { $sectionCount = static::where('category_id', $this->category_id)->where('page_id', $this->page_id)->count(); if ($sectionCount >= self::MAX_SECTIONS) { throw new \Exception('Cannot create more than ' . self::MAX_SECTIONS . ' sections per category.'); } } /** * Validates that the minimum number of sections is maintained. * * @throws \Exception If deletion would violate the minimum section requirement. */ protected static function validateMinSectionCount(self $approach): void { $sectionCount = static::where('category_id', $approach->category_id)->where('page_id', $approach->page_id)->count(); if ($sectionCount <= self::MIN_SECTIONS) { throw new \Exception('At least ' . self::MIN_SECTIONS . ' sections are required per category.'); } } /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $approach) { $approach->validateMaxSectionCount(); $approach->picture = FileStorageHelper::storeFile($approach, $approach->picture, true); }); static::updating(function (self $approach) { $approach->picture = FileStorageHelper::storeFile($approach, $approach->picture, true); }); static::updated(function (self $approach) { FileStorageHelper::removeOldFile($approach, 'picture'); }); static::deleting(function (self $approach) { static::validateMinSectionCount($approach); }); static::deleted(function (self $approach) { FileStorageHelper::removeFile($approach, 'picture'); }); } /** * Relationship: belongs to a category approach * * @return BelongsTo Returns the associated category */ public function category(): BelongsTo { return $this->belongsTo(CategoryApproach::class, 'category_id'); } /** * Relationship: belongs to a static page * * @return BelongsTo Returns the associated static page */ public function page(): BelongsTo { return $this->belongsTo(StaticPage::class); } }