Skip to content
Advertisement

Is there a better way to check for mandatory child in HasMany in Laravel?

I have a class AdBannerModel with an HasMany relationship to BannerLocalizedContentModel. When validating the model I call the method alterRulesForSaving where i want to check that the given AdBanner has at least the mandatory localizedContents. This is how I handle the check now, looking for suggestions.

        $linkTextPresent = false;
        $linkUrlPresent = false;
        $descriptionPresent = false;
        
        /** @var BannerLocalizedContentModel $localizedContent */
        foreach ($this->localizedContents() as $localizedContent) {
            if ($localizedContent->type === BannerLocalizedContentModel::TYPE_LINK_URL) {
                $linkUrlPresent = true;
            }

            if ($localizedContent->type === BannerLocalizedContentModel::TYPE_LINK_TEXT) {
                $linkTextPresent = true;
            }

            if ($localizedContent->type === BannerLocalizedContentModel::TYPE_DESCRIPTION) {
                $descriptionPresent = true;
            }
        }

        if (!$linkUrlPresent || !$linkTextPresent || !$descriptionPresent) {
            throw new ValidationErrorException(['content_i18n' => 'missing mandatory content.'], 'error.invalid_data');
        }

Advertisement

Answer

you can check existence of relation with needed params

// assuming you provide AdBannerModel code

// your HasMany relation
public function bannerLocalizedContentModels() {
  return $this->hasMany(BannerLocalizedContentModel::class);
}

public function alterRulesForSaving(/*params if any*/) {
  //...
  $mandatoryContents = [
    BannerLocalizedContentModel::TYPE_LINK_URL,
    BannerLocalizedContentModel::TYPE_LINK_TEXT,
    BannerLocalizedContentModel::TYPE_DESCRIPTION
  ];
  if ($this->bannerLocalizedContentModels()->whereIn('type', $mandatoryContents)->doesntExist()) {
    throw new ValidationErrorException(['content_i18n' => 'missing mandatory content.'], 'error.invalid_data');
  }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement