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

99 lines
2.6 KiB
PHP
Raw Normal View History

<?php
namespace App\Models;
2022-12-12 17:24:53 +01:00
use App\Casts\RgbaColor;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Range extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'label',
'slug',
'seo_title',
'seo_description',
'color',
'picture',
'picture_alt',
'picture_title',
'picture_banner',
'picture_banner_alt',
'picture_banner_title',
2022-12-12 17:24:53 +01:00
'order'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
2022-12-12 17:24:53 +01:00
'color' => RgbaColor::class
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function () {
throw new \RuntimeException('Impossible de créer un range');
});
static::updating(function (self $model) {
static::assertLabelIsUnique($model->label, $model->id);
2022-12-07 14:31:54 +01:00
$model->slug = Str::slug($model->label);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
$model->picture_banner = FileStorageHelper::storeFile($model, $model->picture_banner, true);
});
static::updated(function (self $model) {
$model->picture = FileStorageHelper::removeOldFile($model, 'picture');
$model->picture_banner = FileStorageHelper::removeOldFile($model, 'picture_banner');
});
static::deleting(function () {
throw new \RuntimeException('Impossible de supprimer un range');
});
}
// * METHODS
/**
* Asserts using validation that the label is unique
*
* @param mixed $label
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If an actu label already exists.
*/
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 subranges for the Range.
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function subranges()
{
return $this->hasMany(Subrange::class);
}
}