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

kortby's avatar
Level 14

how to validate input with other inputs with other array of inputs if it's unique?

I have the following inputs: input name, status(active), servers(array of checkbox), formats(array of multiple formats with four inputs of selects different format), schedules( array of multiple dates) all of those together if active and they are not unique, it causes a conflict I need some sort of validation

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

This can be done, but the tricky part is figuring out how to display the error since there are so many fields to consider. Which field should get the validation error message, or should they all? Or do you want to have this error displayed separately?

I think I'd use a regular validator instance to do all of your normal validation, and then use an after hook to do your custom validation, and make a new "field" to display that special error.

// all of your regular validation
$validator = Validator::make(...);

// special validation for your complex unique rule
$validator->after(function ($validator) {
    // create a query to see if this record already exists.
    $exists = YourModel::where('param1', $request->param1)
        ->where(more conditions from $request)
        ->where(more conditions)
        ->exists();

    if ($exists) {
        $validator->errors()->add('specialField', 'The combination of blah blah fields must be unique');
    }
});

And then in your view, just display the error message for specialField separately, like after your other fields. It wouldn't be an actual form field.

https://laravel.com/docs/5.7/validation#after-validation-hook

1 like
kortby's avatar
Level 14

Hey, @cronix Thank you for you help, but I'm still having issues with this validation, the params are coming from different tables, server table, fromat table, schedule table, so didn't know how make it work like you said, also a have to check if the schedule conflicts with other existing schedules if all matches

Cronix's avatar

You can do as many queries/use as many models as you need within that closure and do whatever checking/comparisons you need. I was just giving a generic example using a single model.

If there is an error, all you really have to do is specify the fieldname the error belongs to along with your custom error message.

if (someCondition) {
    $validator->errors()->add('specialField', 'The combination of blah blah fields must be unique');
}

if (someOtherCondition) {
    $validator->errors()->add('specialField', 'Different error message');
}

Please or to participate in this conversation.