*/ protected $fillable = [ 'title', 'subtitle', 'description', 'slug', 'picture', 'picture_alt', 'picture_title', ]; /** * Perform any actions required after the model boots. */ 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. * * @throws \Illuminate\Validation\ValidationException If an actu title already exists. */ private static function assertTitleIsUnique(?string $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. */ private static function resetCache(): void { Cache::forget('consumptionMomentsOrderedBySlug'); self::getOrderedBySlug(); } /** * Get all consumption moments ordered by slug. */ public static function getOrderedBySlug(): Collection { return Cache::remember('consumptionMomentsOrderedBySlug', 86400, function () { return self::query()->orderBy('slug')->get(); }); } // * RELATIONSHIPS /** * Get all of the recipes for the consumption moment. */ public function recipes(): BelongsToMany { return $this->belongsToMany(Recipe::class); } }