ldc-showroom-bo/app/Models/Product.php
2024-01-05 17:36:16 +01:00

97 lines
3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
/**
* @property string $name Name of the product.
* @property string $slug Slug of the name for the product.
* @property string $description WYSIWYG text description using ckeditor.
* @property string $picture Picture path for the product.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \App\Models\Range $range Range Belongs-to.
*/
class Product extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'description',
'picture',
'range_id',
];
/**
* 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 the range that owns the Product
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function range(): BelongsTo
{
return $this->belongsTo(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);
}
}