ldc-le-gaulois-pro/app/Models/Subrange.php

94 lines
2 KiB
PHP
Raw Normal View History

<?php
namespace App\Models;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Subrange extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'label',
'slug',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
}
// * METHODS
/**
* Undocumented function
*
* @param Model $model
* @return void
*/
private static function manageFields(Model $model)
{
// * ASSERTIONS
static::assertLabelIsUnique($model->label, $model->id);
// * TRANSFORMATIONS
$model->slug = Str::slug($model->label);
}
/**
* Asserts using validation that the label is unique
*
* @param mixed $label
* @param integer|null $id
* @return void
*/
private static function assertLabelIsUnique($label, ?int $id = null)
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'label', $label, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($label), $id);
}
// * RELATIONSHIPS
/**
* Get products for the Subrange.
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function products()
{
return $this->hasMany(Product::class);
}
/**
* Get range for the Subrange.
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function range()
{
return $this->belongsTo(Range::class);
}
}