ldc-volena/app/Models/Carousel.php
2026-04-24 15:06:55 +02:00

102 lines
2.6 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use App\Traits\Models\Orderable;
use Illuminate\Database\Eloquent\Model;
/**
* @property-read int $id Id.
* @property string $title Title.
* @property array $media Medias of the carousel.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
*
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/
class Carousel extends Model
{
use ActivityLog;
use Orderable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'section_id',
'title',
'media',
'order',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'media' => 'array',
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
$otherCarousels = self::query()
->whereRelation('section', 'id', $model->section->id)
->count();
if ($otherCarousels > 4) {
throw new \RuntimeException('Creating more than 5 carousels is not allowed');
}
self::setOrder($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFiles(
data_get(ToolboxHelper::getOriginal($model, 'media'), 'pictures.*.path', ['']),
data_get($model->media, 'pictures.*.path', [''])
);
});
static::deleted(function (self $model) {
FileStorageHelper::removeOldFiles(
data_get($model->media, 'pictures.*.path', ['']),
['']
);
self::setOrder($model, true);
});
}
// * METHODS.
/**
* Group ordering by section_id.
*
* @return string
*/
public function getOrderGroupField(): string
{
return 'section_id';
}
// * RELATIONSHIPS.
/**
* Get the sections that owns the Carousel
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Section,$this>
*/
public function section(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Section::class);
}
}