$ranges Ranges Has-many relationship.
*/
class Brand extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'color',
'picture',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'color' => HtmlColor::class
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// * ASSERTIONS
static::assertNameIsUnique($model->name);
// * TRANSFORMATIONS
$model->slug = Str::slug($model->name);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
});
static::updating(function (self $model) {
// * ASSERTIONS
static::assertNameIsUnique($model->name, $model->id);
// * TRANSFORMATIONS
$model->slug = Str::slug($model->name);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
});
}
// * RELATIONSHIPS
/**
* Get all of the ranges for the Brand
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function ranges(): HasMany
{
return $this->hasMany(Range::class);
}
// * 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);
}
}