131 lines
3 KiB
PHP
131 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\ToolboxHelper;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
class Gamme extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* Fillable fields.
|
|
*
|
|
* @var array
|
|
*/
|
|
#[\Override]
|
|
protected $fillable = [
|
|
'parent_gamme_id',
|
|
'title',
|
|
'slug',
|
|
'text',
|
|
'picture1',
|
|
'alt_text_picture1',
|
|
'picture2',
|
|
'alt_text_picture2',
|
|
'picture3',
|
|
'alt_text_picture3',
|
|
'category',
|
|
];
|
|
|
|
/**
|
|
* The "booted" method of the model.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function boot(): void
|
|
{
|
|
static::creating(function (Gamme $gamme): void {
|
|
$gamme->updateImages($gamme);
|
|
});
|
|
|
|
static::updating(function (Gamme $gamme): void {
|
|
$gamme->updateImages($gamme);
|
|
});
|
|
|
|
static::deleting(function (Gamme $gamme): void {
|
|
if ($gamme->childGammes()->exists()) {
|
|
Gamme::whereParentGammeId($gamme->id)
|
|
->update(['parent_gamme_id' => null]);
|
|
}
|
|
});
|
|
|
|
static::deleted(function (Gamme $gamme): void {
|
|
$gamme->deleteImages($gamme->picture1);
|
|
$gamme->deleteImages($gamme->picture2);
|
|
$gamme->deleteImages($gamme->picture3);
|
|
});
|
|
|
|
parent::boot();
|
|
}
|
|
|
|
/**
|
|
* Update images.
|
|
*
|
|
* @param Gamme $model
|
|
* @return void
|
|
*/
|
|
private static function updateImages(Gamme $model): void
|
|
{
|
|
if ($model->picture1) {
|
|
$model->picture1 = ToolboxHelper::storeImage($model->picture1, $model->getTable());
|
|
}
|
|
if ($model->picture2) {
|
|
$model->picture2 = ToolboxHelper::storeImage($model->picture2, $model->getTable());
|
|
}
|
|
if ($model->picture3) {
|
|
$model->picture3 = ToolboxHelper::storeImage($model->picture3, $model->getTable());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete images.
|
|
*
|
|
* @param string $target
|
|
* @return void
|
|
*/
|
|
private static function deleteImages(string $target): void
|
|
{
|
|
if ($target) {
|
|
$urlPicture = public_path() . $target;
|
|
if ($urlPicture) {
|
|
if (File::exists($urlPicture)) {
|
|
File::delete($urlPicture);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get Child of the Gamme.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
|
*/
|
|
public function childGammes()
|
|
{
|
|
return $this->hasMany(Gamme::class, 'parent_gamme_id')->orderBy('order');
|
|
}
|
|
|
|
/**
|
|
* Get Gamme.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
*/
|
|
public function parentGamme()
|
|
{
|
|
return $this->belongsTo(Gamme::class);
|
|
}
|
|
|
|
/**
|
|
* Get Products for the Gamme.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
|
*/
|
|
public function products()
|
|
{
|
|
return $this->hasMany(Product::class);
|
|
}
|
|
}
|