*/ protected $fillable = [ 'title', 'subtitle', 'description', 'slug', 'picture', 'picture_alt', 'picture_title', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::assertTitleIsUnique($model->title); $model->slug = Str::slug($model->title); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); }); static::created(function () { self::resetCache(); }); static::updating(function (self $model) { self::assertTitleIsUnique($model->title, $model->getKey()); $model->slug = Str::slug($model->title); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); self::resetCache(); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); self::resetCache(); }); } // * METHODS /** * Asserts using validation that the title is unique. * * @param string|null $title * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If an actu title already exists. */ private static function assertTitleIsUnique(string|null $title, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id); ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id); } /** * Reset all cache elements related to this model. * * @return void */ private static function resetCache(): void { Cache::forget('consumptionMomentsOrderedBySlug'); self::getOrderedBySlug(); } /** * Get all consumption moments ordered by slug. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getOrderedBySlug(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('consumptionMomentsOrderedBySlug', 86400, function () { return self::query()->orderBy('slug')->get(); }); } }