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

TheoR's avatar
Level 14

Validate against three fields

Hello.

I have a somewhat unique case. I have three fields in my database table. Separately, these three fields can have duplicates in the table. However, together, the three fields need to be unique. So, if Field1 has A and Field two Has B and Field has C, then no other record can have "ABC" in those fields together. However "ABD" would be ok, since those three together are unique.

I've been trying to come up with a validation rule for this but am stuck. I did create an attribute in the database to combine the three fields together, but I don't see how that will really help me with this validation rule.

Any suggestions would be greatly appreciated!

Thanks!

0 likes
4 replies
TheoR's avatar
Level 14

@jlrdw I must have figured that out at the same time you posted. That is exactly what I ended up doing!

Thanks!

TheoR's avatar
Level 14

ok, I spoke too soon. I figured out you can add a query to a rule like so:

Rule::unique('my_table')
                    ->where(function ($query) {
                        return $query
                            ->where(
                                'field1',
                                $this->field1
                            )
                            ->where('field2', $this->field2)
                            ->where('field3', $this->field3);
                    })
                    ->ignore($this->id)

This does the trick!

jbloomstrom's avatar

You can also enforce this at the database level with a unique index.

$table->unique(['field1','field2','field3']);

Please or to participate in this conversation.