107 lines
2.8 KiB
PHP
107 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Contracts\TranslatableModel;
|
|
use App\Helpers\TranslationHelper;
|
|
use App\Traits\Models\HasCache;
|
|
use App\Traits\Models\HasTranslations;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Support\Str;
|
|
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
|
|
|
|
/**
|
|
* @property int $id
|
|
* Id of the news.
|
|
* @property string $name
|
|
* Name of the category.
|
|
* @property-read \Illuminate\Support\Carbon $created_at
|
|
* Date on which the category was created.
|
|
* @property-read \Illuminate\Support\Carbon $updated_at
|
|
* Date on which the category was updated.
|
|
* @property \Illuminate\Database\Eloquent\Collection<int, \App\Models\News> $news
|
|
* Associated news of the category.
|
|
*/
|
|
class NewsCategory extends Model implements TranslatableModel
|
|
{
|
|
use ActivityLog;
|
|
use HasFactory;
|
|
use HasCache;
|
|
use HasTranslations;
|
|
use SoftDeletes;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var list<string>
|
|
*/
|
|
protected $fillable = [
|
|
'name',
|
|
'slug',
|
|
'color',
|
|
];
|
|
|
|
/**
|
|
* The translatable columns.
|
|
*
|
|
* @var list<string>
|
|
*/
|
|
public $translatable = [
|
|
'name',
|
|
'slug'
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (self $model) {
|
|
self::manageFields($model);
|
|
});
|
|
static::updating(function (self $model) {
|
|
self::manageFields($model);
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Manage model fields.
|
|
*
|
|
* @param self $model
|
|
* @return void
|
|
*/
|
|
private static function manageFields(self $model): void
|
|
{
|
|
// Check unique fields.
|
|
$slug = Str::slug($model->name);
|
|
TranslationHelper::assertTranslationFieldIsUnique($model, $model->name, 'name');
|
|
TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'name');
|
|
$model->setAttribute('slug', $slug);
|
|
// Check translations.
|
|
TranslationHelper::validateFallbackTranslations($model);
|
|
}
|
|
|
|
// * RELATIONSHIPS
|
|
|
|
/**
|
|
* Associated news of the category.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
|
|
*/
|
|
public function news(): \Illuminate\Database\Eloquent\Relations\MorphToMany
|
|
{
|
|
return $this->morphToMany(
|
|
News::class,
|
|
'newsable',
|
|
'newsables',
|
|
'news_id',
|
|
'newsable_id'
|
|
);
|
|
}
|
|
}
|