*/ protected $fillable = [ 'seo_title', 'seo_description', 'label', 'picture', 'picture_alt', 'picture_title', 'picture_thumbnail', 'picture_thumbnail_alt', 'picture_thumbnail_title', 'description', 'nutriscore', 'nutritionnal_values', 'advice', 'ingredients', 'published', 'order', 'range_id', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published' => 'boolean', 'nutriscore' => \App\Enums\Products\NutriscoreEnum::class, 'nutritionnal_values' => 'array' ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::manageFields($model); self::setOrder($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); FileStorageHelper::removeOldFile($model, 'picture_thumbnail'); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); FileStorageHelper::removeFile($model, 'picture_thumbnail'); }); } // * METHODS /** * Manage model fields. * * @param self $model * @return void */ private static function manageFields(self $model): void { // * ASSERTIONS self::assertFieldIsUnique('label', $model->label, $model->id); self::assertFieldIsUnique('slug', Str::slug($model->label), $model->id); // * TRANSFORMATIONS $model->slug = Str::slug($model->label); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); $model->picture_thumbnail = FileStorageHelper::storeFile($model, $model->picture_thumbnail, true); } /** * 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; } /** * Asserts using validation that the field is unique. * * @param string $nameField * @param string $valueField * @param integer|null $id * @return void */ private static function assertFieldIsUnique(string $nameField, string $valueField, ?int $id = null): void { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id); } // * RELATIONS /** * Get the range that owns the product. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function range(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Range::class); } /** * The pictos that belong to the product. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function pictos(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->belongsToMany(Picto::class); } }