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

oldgit's avatar

Validation - unique within subset of records

I'm trying to validate a piece of data against a subset of records in a table. The big picture is that I have a table of competiton entries for multiple competitions. Each entry must have a unique number (to be displayed by the entrant) for obvious reasons. The Entry table includes a field - competitionID - which links the Entry to the Competition. I can easily use the 'unique' validator to validate against the whole entries table. Any suggestions for how I can validate it, in simple terms, 'unique where competitionID = $x'

TIA, Alex

0 likes
6 replies
vincent15000's avatar

You have to create a custom Rule.

public function rules(): array
{
    return [
        'competition_id' => ['required', 'exists:competitions,id'],
        'number' => [
            'required',
            Rule::unique('entries', 'number')
                ->where(function ($query) {
                    $query->where('competition_id', $this->competition_id);
                }),
        ],
    ];
}
1 like
oldgit's avatar

Thanks, I'll have a look at that.

1 like
vincent15000's avatar

You can also enhance this by adding a unique constraint in the database.

$table->unique(['number', 'competition_id']);
1 like

Please or to participate in this conversation.