*/ protected $fillable = [ 'name', 'color', 'published', ]; /** * The translatable columns. * * @var list */ public $translatable = [ 'name', ]; /** * 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::manageFields($model); }); static::created(function (self $model) { self::resetCache(); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function () { self::resetCache(); }); static::deleted(function () { self::resetCache(); }); static::restored(function () { self::resetCache(); }); static::forceDeleted(function () { self::resetCache(); }); } // * METHODS /** * Manage model fields. * * @param self $model * @return void */ private static function manageFields(self $model): void { TranslationHelper::assertTranslationFieldIsUnique($model, $model->name, 'name'); self::validateFallbackTranslations($model); } /** * Assert fallback locale translation is present. * * @param self $model * @return void * @throws \Illuminate\Validation\ValidationException Translations missing. */ public static function validateFallbackTranslations(self $model): void { if (!$model->published) { return; } TranslationHelper::validateFallbackTranslations($model); } /** * Reset all cache elements related to this model. * * @return void */ public static function resetCache(): void { Cache::forget('allCompanyActivities'); self::getAllCompanyActivities(); Cache::forget('publishedCompanyActivities'); self::getPublishedCompanyActivities(); } /** * Get all company activities. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getAllCompanyActivities(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('allCompanyActivities', 86400, function () { return self::query()->get(); }); } /** * Get all published company activities. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getPublishedCompanyActivities(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('publishedCompanyActivities', 86400, function () { return self::getAllCompanyActivities()->where('published', true); }); } }