*/ protected $fillable = [ 'year', 'title', 'description', 'picture', 'picture_alt', 'picture_title', 'video_id', 'picto', 'picto_alt', 'picto_title', 'picto_position', 'order', 'published', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'year' => 'integer', 'picto_position' => HistoricalMilestonePosition::class, 'published' => 'boolean', ]; /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $historicalMilestone) { self::setOrder($historicalMilestone); self::setImage($historicalMilestone, 'picture'); self::setImage($historicalMilestone, 'picto'); }); static::created(function () { self::resetCache(); }); static::updating(function (self $historicalMilestone) { self::setImage($historicalMilestone, 'picture'); self::setImage($historicalMilestone, 'picto'); }); static::updated(function (self $historicalMilestone) { FileStorageHelper::removeOldFile($historicalMilestone, 'picture'); FileStorageHelper::removeOldFile($historicalMilestone, 'picto'); self::resetCache(); }); static::deleted(function (self $historicalMilestone) { FileStorageHelper::removeFile($historicalMilestone, 'picture'); FileStorageHelper::removeFile($historicalMilestone, 'picto'); self::resetCache(); }); } // * METHODS /** * Set model's published date. */ private static function setImage(self $historicalMilestone, string $field): void { if (is_null($historicalMilestone->{$field})) { $historicalMilestone->{$field . '_alt'} = null; $historicalMilestone->{$field . '_title'} = null; } else { $historicalMilestone->{$field} = FileStorageHelper::storeFile( $historicalMilestone, $historicalMilestone->{$field}, true ); } } /** * Set order after the last element of the list. */ private static function setOrder(self $model): void { $model->order = \intval(self::query()->max('order')) + 1; } /** * Reset all cache elements related to this model. */ private static function resetCache(): void { Cache::forget('publishedHistoricalMilestonesOrdered'); self::getPublishedOrdered(); } /** * Get all published HistoricalMilestones ordered. */ public static function getPublishedOrdered(): Collection { return Cache::remember('publishedHistoricalMilestonesOrdered', 86400, function () { return self::query()->where('published', true)->orderBy('order')->get(); }); } }