'json', 'difficulty' => DifficultyEnum::class ]; /** * The translatable columns. * * @var array */ public $translatable = [ 'seo_title', 'seo_description', 'name', 'slug', 'picture', 'picture_alt', 'picture_title', 'picture_thumbnail', 'picture_thumbnail_alt', 'picture_thumbnail_title', 'ingredients', 'duration', 'teaser', 'steps', 'tips', ]; // * EVENTS /** * Perform any actions required after the model boots. * * @return void */ protected static function booted() { static::creating(function (self $model) { self::assertFieldIsUnique('name', $model->name); self::setSlug($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 /** * Common methods function. * * @param Model $model * @return void */ private static function manageFields(Model $model) { if (is_array($model->ingredients)) { foreach ($model->ingredients as $itemIngredients) { if (isset($itemIngredients['header'])) { ToolboxHelper::assertNoInternalBoUrls('ingredients', $itemIngredients['header']); } ToolboxHelper::assertNoInternalBoUrls('ingredients', \strval($itemIngredients['value'])); } } ToolboxHelper::assertNoInternalBoUrls('steps', $model->steps); ToolboxHelper::assertNoInternalBoUrls('tips', $model->tips); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); $model->picture_thumbnail = FileStorageHelper::storeFile($model, $model->picture_thumbnail, true); } /** * Set the slug. * * @param \Illuminate\Database\Eloquent\Model $model * * @return void */ private static function setSlug(Model $model) { $model->slug = Str::slug($model->name); } /** * Set order after the last element of the list. * * @param \Illuminate\Database\Eloquent\Model $model * @return void */ private static function setOrder(Model $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) { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id); } // * RELATIONSHIPS /** * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function products() { return $this->belongsToMany(Product::class, 'recipes_products'); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function range() { return $this->belongsTo(Range::class); } }