Search code examples
laravelvalidation

Laravel: Add "required" rule if wildcard matches "gb" in languages.*.description


Right now I have this rule:

    public function rules(): array
    {
        return [
            'languages.*.description' => ['string', 'required'],
        ];
    }

What I need is to exclude required if the wildcard equals gb. I could do something like this but it feels clunky:

    public function rules(): array
    {
        return [
            'languages.no.description' => ['string', 'required'],
            'languages.nl.description' => ['string', 'required'],
            'languages.gb.description' => ['string'],
        ];
    }


Solution

  • I don't think it's clunky, if this often changes what you could do is create an array that holds your languages.

    protected $languages = [
        'no' => true,
        'nl' => true,
        'gb' => true,
    ];
    
    public function rules(): array
    {
        $rules = [];
        foreach ($this->languages as $language => $isRequired) {
            $rules["languages.$language.description"] = $isRequired ? ['required', 'string'] : ['string'];
        }
        return $rules;
    }