skip to Main Content

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'],
        ];
    }

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. You can do this if you put the gb rule last e.g. :

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

    Though this does not seem documented and may change in the future.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search