*/ protected $fillable = [ 'name', 'description', 'picture', 'status', 'range_id', ]; /** * Translatable fields array * * @var array */ public $translatable = [ 'name', 'slug', 'description', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'status' => 'bool', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { // * ASSERTIONS self::assertNameIsUnique($model->name); // * TRANSFORMATIONS $model->slug = Str::slug($model->name); /** @phpstan-ignore-next-line */ if ($model->picture instanceof UploadedFile) { $model->picture = ShowroomFileHelper::storeFileWithUUIDName($model->picture, $model); } }); static::updating(function (self $model) { // * ASSERTIONS self::assertNameIsUnique($model->name, $model->id); // * TRANSFORMATIONS $model->slug = Str::slug($model->name); /** @phpstan-ignore-next-line */ if ($model->picture instanceof UploadedFile) { $model->picture = ShowroomFileHelper::storeFileWithUUIDName($model->picture, $model); } }); static::updated(function (self $model) { FileHelper::removeOldFile($model, 'picture'); }); static::deleted(function (self $model) { FileHelper::removeFile($model, 'picture'); }); } // * RELATIONSHIPS /** * Get the range that owns the Product * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function range(): BelongsTo { return $this->belongsTo(Range::class); } /** * Get the brand that owns the Product * * @return \Illuminate\Database\Eloquent\Relations\HasOneThrough */ public function brand(): HasOneThrough { return $this->hasOneThrough(Brand::class, Range::class, 'id', 'id', 'range_id', 'brand_id'); } // * METHODS /** * Asserts using validation that the name is unique * * @param string|null $name * @param integer|null $id * @return void * @throws \Illuminate\Validation\ValidationException If name already exists. */ private static function assertNameIsUnique(string|null $name, ?int $id = null) { $table = (new self())->getTable(); ToolboxHelper::assertFieldIsUnique($table, 'name', $name, $id); ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($name), $id); } }