*/ protected $fillable = [ 'name', 'title', 'text', 'picture', 'picture_alt', 'picture_title', 'published', 'network_id', 'order', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published' => 'boolean', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::creating(function (self $model) { self::setOrder($model); self::manageFields($model); }); static::updating(function (self $model) { self::manageFields($model); }); static::updated(function (self $model) { FileStorageHelper::removeOldFile($model, 'picture'); }); static::deleting(function (self $model) { self::assertLimitPublishedModels($model, true); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); self::setOrder($model, true); }); } // * METHODS. /** * Manage model fields. * * @param self $model * @return void */ private static function manageFields(self $model): void { // * ASSERTIONS self::assertLimitPublishedModels($model); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); } /** * Check if the limit of published models is reached. * * @param self $model * @param boolean $isDeletion * @throws \Illuminate\Validation\ValidationException If the limit of published models is reached. * @return void */ private static function assertLimitPublishedModels(self $model, bool $isDeletion = false) { $count = self::query() ->where('published', true) ->where('network_id', $model->network_id) ->count(); $updatePublished = !$isDeletion && $model->published && !$model->getOriginal('published'); if ( (!$model->published && $count <= 1) || ($updatePublished && $count >= 4) || ($isDeletion && $count === 1) ) { throw ValidationException::withMessages([ 'Il doit y avoir entre 1 et 4 éléments attachés à chaque réseau.' ]); } } /** * Group ordering by network_id. * * @return string */ public function getOrderGroupField(): string { return 'network_id'; } // * RELATIONS. /** * The network that belongs to the logo. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\Network,$this> */ public function network(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Network::class); } /** * Associated brands. * * @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Brand,$this> */ public function brands(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Brand::class); } }