ExpertiseProductPageEnum::class, 'nutriscore' => NutriscoreEnum::class ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'points' => 'array', 'is_frenchpoultry' => 'bool', 'is_natureeleveurs' => 'bool' ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted() { static::creating(function (self $model) { self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); FileStorageHelper::removeOldFile($model, 'picture2'); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); FileStorageHelper::removeFile($model, 'picture2'); }); } // * METHODS /** * Undocumented function * * @param Model $model * @return void */ private static function manageFields(Model $model) { static::assertFieldIsUnique('label', $model->label, $model->id); static::assertFieldIsUnique('title', $model->title, $model->id); self::assertNumberOfProductsVip($model->page->value); } /** * Asserts using validation that the label is unique * * @param string $name * @param mixed $field * @param integer|null $id * @return void */ private static function assertFieldIsUnique(string $name, $field, ?int $id = null) { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, $name, $field, $id); } /** * Asserts the number of products in the specie. * * @param integer $specie * @return void * @throws \Illuminate\Validation\ValidationException If there are more than 3 products. */ private static function assertNumberOfProductsVip(int $specie) { if (count(self::where('page', '=', $specie)->get()) >= 3) { throw ValidationException::withMessages([ 'Opération impossible, maximum 3 produits peuvent être présents.' ]); } } }