Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

timkariuki's avatar

How do I validate a nested array attribute based on another attribute in Laravel?

I am uploading data from excel then validating it. I want to validate the date of employment based on the date of birth in the same row. I am having to get the date of birth from the entire imported array for each row, which is impacting performance.

My validation code is as follows:

     $validator = Validator::make($staff, [
        '*.DateofBirth' => ["date"],
        '*.DateofEmployment' => [
            function ($attr, $value, $fail) use ($staff) {
                $staff_info = $staff[(int)explode(".", $attr)[0]]; // Getting same row data here
                if (isset(($staff_info)["DateofBirth"])) {
                    $dob_is_valid = strtotime(($staff_info)["DateofBirth"]);
                    $doe_is_valid = strtotime($value);
                    if ($dob_is_valid && $doe_is_valid) {
                        $date = Carbon::parse($value);
                        $dob = Carbon::parse($staff_info["DateofBirth"]);
                        if ($dob->addYears(18)->isAfter($date)) {
                            $fail('The :attribute must be at least 18 years after Date of Birth');
                        }
                    }
                }

            },
        ],
    ]);

Is there a better way of accessing the same row attributes?

0 likes
1 reply

Please or to participate in this conversation.