0

In my form the user can add (or remove) licence items which are generated as input nested arrays:

<div>
    <select name="licences[0][type]">
        <option value="">- Select -</option>
        <option value="car">Car</option>
        <option value="motorbike">Motorbike</option>
    </select>

    <input type="text" name="licences[0][car_spec]"  value="">
    <input type="text" name="licences[0][motorbike_spec]"  value="">
</div>

<div>
    <select name="licences[1][type]">
        <option value="">- Select -</option>
        <option value="car">Car</option>
        <option value="motorbike">Motorbike</option>
    </select>

    <input type="text" name="licences[1][car_spec]"  value="">
    <input type="text" name="licences[1][motorbike_spec]"  value="">
</div>

...

and here are my rules:

$rules = [
    'licences.*.type' => 'required',
    'licences.*.car_spec' => 'required_if:licences.*.type|car',
    'licences.*.motorbike_spec' => 'required_if:licences.*.type|motorbike',
];

Now how can I ensure that the validations match the same index (*) of the licences array ?
For instance, the licences[1][car_spec] input is checked against the licences[1][type] input and not against the licences[0][type].

1 Answer 1

1

try like this one:

public function validation(){
    $rules = [
        'licences.*.type' => 'required',
        'licences.*.car_spec' => 'required_if:licences.*.type|car',
        'licences.*.motorbike_spec' => 'required_if:licences.*.type|motorbike',
    ];
     foreach($this->request->get('licences') as $key => $value){
         $rules['licences.'.$key.'.type'] = 'required';
         $rules['licences.'.$key.'.car_spec'] = 'required_if:licences.*.type|car';
         $rules['licences.'.$key.'.motorbike_spec'] = 'required_if:licences.*.type|motorbike';
     }
    return $rules;
}

I hope this works for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.