*/ protected $fillable = [ 'catchline', 'content', 'identity', 'job', 'picture', 'picture_alt', 'picture_title', 'video_id', 'published', 'order', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published' => 'boolean', ]; /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $model) { self::setOrder($model); self::manageFields($model); }); static::created(function () { self::resetCache(); }); static::updating(function (self $model) { self::manageFields($model); }); 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->picture = FileStorageHelper::storeFile($model, $model->picture, true); self::checkPublishedCount($model, 5); } /** * Set order after the last element of the list. */ private static function setOrder(self $model): void { $model->order = \intval(self::query()->max('order')) + 1; } /** * Check if the max amount of published models is reached. */ private static function checkPublishedCount(self $model, int $max): void { Validator::make(['published' => $model->published], [ 'published' => Rule::prohibitedIf( $model::where('published', true)->count() >= $max && $model->published === true && $model->published !== $model->getOriginal('published') ), ], [ 'published.prohibited' => trans('Il ne peut y avoir que :max :model:plural publié:plural en même temps.', [ 'max' => $max, 'model' => trans('models.classes.testimonial'), 'plural' => $max > 1 ? 's' : '', ]), ])->validate(); } /** * Reset all cache elements related to this model. */ private static function resetCache(): void { Cache::forget('publishedTestimonialsOrderedByOrder'); self::getPublishedOrdered(); } /** * Get all published Testimonials ordered by order. */ public static function getPublishedOrdered(): Collection { return Cache::remember('publishedTestimonialsOrderedByOrder', 86400, function () { return self::query()->where('published', true)->orderBy('order')->get(); }); } }