*/ protected $fillable = [ 'section_id', 'title', 'media', 'order', 'published', ]; /** * The attributes that should be cast. * * @var array */ 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 /** * Set order after the last element of the list. * * @param self $model * @param boolean $isDeletion * @return void */ private static function setOrder(self $model, bool $isDeletion = false): void { $maxOrder = \intval(self::query()->where('section_id', $model->section_id)->max('order')); if ($isDeletion) { $request = Carousel::query() ->where('section_id', $model->section_id) ->whereNot('id', $model->id) ->whereBetween('order', [$model->order, $maxOrder]); $request->decrement('order', 1); return; } $model->order = $maxOrder + 1; } // * RELATIONSHIPS /** * Get the sections that owns the Carousel * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function section(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Section::class); } }