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

oldgit's avatar

oldgit liked a comment+100 XP

4mos ago

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

$table->unique(['number', 'competition_id']);
oldgit's avatar

oldgit wrote a reply+100 XP

4mos ago

Thanks, I'll have a look at that.

oldgit's avatar

oldgit liked a comment+100 XP

4mos ago

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);
                }),
        ],
    ];
}
oldgit's avatar

oldgit started a new conversation+100 XP

4mos ago

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