*/
protected $fillable = [
'title',
'seo_title',
'seo_description',
'color',
'slug',
'published',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'color' => HtmlColor::class,
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*/
protected static function booted(): void
{
static::creating(function (self $newsCategory) {
self::assertTitleIsUnique($newsCategory->title);
self::setOrder($newsCategory);
self::manageFields($newsCategory);
});
static::created(function () {
self::resetCache();
News::resetCache();
});
static::updating(function (self $newsCategory) {
self::assertTitleIsUnique($newsCategory->title, $newsCategory->getKey());
self::manageFields($newsCategory);
});
static::updated(function () {
self::resetCache();
News::resetCache();
});
static::deleted(function () {
self::resetCache();
News::resetCache();
});
}
// * METHODS
/**
* Set model's order after the last element of the list.
*/
private static function setOrder(self $model): void
{
$model->order = \intval(self::query()->max('order')) + 1;
}
/**
* Manage model fields.
*/
private static function manageFields(self $model): void
{
$model->slug = Str::slug($model->title);
}
/**
* Asserts using validation that the title is unique.
*
* @throws \Illuminate\Validation\ValidationException If an news category 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('publishedNewsCategoriesOrderedByOrder');
self::getPublishedOrdered();
}
/**
* Get all published NewsCategories ordered by order.
*/
public static function getPublishedOrdered(): Collection
{
return Cache::remember('publishedNewsCategoriesOrderedByOrder', 86400, function () {
return self::query()->where('published', true)->orderBy('order')->get();
});
}
/**
* Create a SchemaOrg.
*/
public function toSchemaOrg(): DefinedTermSet
{
return Schema::definedTermSet()
->hasDefinedTerm(
Schema::definedTerm()
->name($this->seo_title)
->description($this->seo_description)
);
}
}