*/
protected $fillable = [
'label',
'slug',
'description',
'banner',
'banner_alt',
'banner_title',
'color',
'published',
'order',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'color' => HtmlColor::class,
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// * ASSERTIONS
self::assertLabelIsUnique($model->label);
self::setOrder($model);
self::manageFields($model);
});
static::updating(function (self $model) {
// * ASSERTIONS
self::assertLabelIsUnique($model->label, $model->id);
self::manageFields($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'banner');
});
static::deleting(function (self $model) {
/** @var \Illuminate\Database\Eloquent\Collection $submeats */
$submeats = $model->submeats;
if ($submeats->isNotEmpty()) {
session()->flash('error', __('Des sous-viandes sont associées à cette viande.
// Veuillez supprimer les sous-viandes concernées ou les réassocier à une autre viande.'));
return false;
}
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'banner');
});
}
// * METHODS
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
$model->slug = Str::slug($model->label);
$model->banner = FileStorageHelper::storeFile($model, $model->banner, true);
}
/**
* Asserts using validation that the label is unique
*
* @param string|null $label
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If a meat label already exists.
*/
private static function assertLabelIsUnique(string|null $label, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($label), $id);
}
/**
* Set order after the last element of the list.
*
* @param self $model
* @return void
*/
private static function setOrder(self $model): void
{
$model->order = \intval(self::query()->max('order')) + 1;
}
// * RELATIONSHIPS
/**
* Get all of the products for the meat.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function products(): MorphToMany
{
return $this->morphToMany(Product::class, 'productable');
}
/**
* Get the related submeats.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function submeats(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Submeat::class);
}
}