ldc-le-gaulois-pro/app/Models/Subrange.php
2024-06-07 16:07:12 +02:00

102 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* @property integer $id Id.
* @property string $label Label.
* @property string $slug Slug of the label.
* @property integer $range_id Foreign key Range.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Product> $products
* Products Belongs-To-Many relationship.
* @property-read \App\Models\Range $range Range Belongs-To relationship.
*/
class Subrange extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'label',
'slug',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
}
// * METHODS
/**
* Common methods function.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
self::assertLabelIsUnique($model->label, $model->id);
$model->slug = Str::slug($model->label);
}
/**
* Asserts using validation that the label is unique
*
* @param string $label
* @param integer|null $id
* @return void
*/
private static function assertLabelIsUnique(string $label, ?int $id = null): void
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($label), $id);
}
// * RELATIONSHIPS
/**
* Products Belongs-To-Many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function products(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Product::class);
}
/**
* Range Belongs-To relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function range(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Range::class);
}
}