*/ 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. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::setOrder($model); self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); 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->picture = FileStorageHelper::storeFile($model, $model->picture, true); self::checkPublishedCount($model, 5); } /** * Set order after the last element of the list. * * @param self $model * @return void */ 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. * * @param self $model * @param integer $max * @return void */ private static function checkPublishedCount(self $model, int $max) { 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' => str(__('models.classes.testimonial')), 'plural' => $max > 1 ? 's' : '', ]) ])->validate(); } }