PublishedStatus::class ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published_at' => 'datetime' ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted() { static::creating(function (self $model) { static::assertTitleIsUnique($model->title); ToolboxHelper::assertNoInternalBoUrls('content', $model->content); $model->slug = Str::slug($model->title); $model->content = clean($model->content); $model->picture = FileStorageHelper::storeFile($model, $model->picture); if ($model->published->equals(PublishedStatus::published())) { $model->published_at = now(); } }); static::updating(function (self $model) { static::assertTitleIsUnique($model->title, $model->id); ToolboxHelper::assertNoInternalBoUrls('content', $model->content); $model->slug = Str::slug($model->title); $model->content = clean($model->content); // * Update published_at it publish status changed if ( $model->published->value != $model->getOriginal('published') and $model->published->equals(PublishedStatus::published()) ) { $model->published_at = now(); } // * Store new picture if changed if ($model->picture != $model->getOriginal('picture')) { $model->picture = FileStorageHelper::storeFile($model, $model->picture); } }); static::updated(function (self $model) { ToolboxHelper::removeUnusedImagesOnCkEditor($model, 'content'); if ($model->picture != $model->getOriginal('picture')) { $model->picture = FileStorageHelper::removeOldFile($model, 'picture'); } }); static::deleting(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); ToolboxHelper::removeImagesOnCkEditor($model, 'content'); }); } /** * Get the route key for the model. * * @return string */ public function getRouteKeyName(): string { return 'slug'; } // * RELATIONSHIPS /** * MorphToMany tags relation * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } // * METHODS /** * Asserts using validation that the title is unique * * @param mixed $title * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If an actu title already exists. */ private static function assertTitleIsUnique($title, ?int $id = null) { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id); ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id); } }