*/ protected $fillable = [ 'name', 'title', 'text', 'picture', 'picture_alt', 'picture_title', 'published', 'network_id', ]; /** * 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::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'); }); } // * 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 * @return void */ private static function assertLimitPublishedModels(self $model, $isDeletion = false) { $count = self::query()->where('published', true)->where('network_id', $model->network_id)->count(); if ( (!$model->published && $count <= 1) || ($model->published && $count >= 4) || ($isDeletion && $count === 1) ) { throw ValidationException::withMessages([ 'Il doit y avoir entre 1 et 4 éléments attachés à chaque réseau.' ]); } } // * RELATIONS /** * The network that belongs to the logo. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function network(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Network::class); } /** * Associated brands. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function brands(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Brand::class); } }